도라에몽 개발자

연산자와 구문 본문

LANGUAGE/JavaScript

연산자와 구문

Doraemon_lulu 2023. 12. 22. 01:00

산술 / 할당 / 증감 연산자

산술 연산자 (Arithmetic)

Ex. 1 + 2

■ 연산자: 기호 (+)

■ 피연산자: 데이터 (1, 2)

  • 나누기 연산자: /
  • 나머지 연산자: %
// 나누기 연산자 (/)
console.log(10 / 2) // 5

// 나머지 연산자 (%)
console.log(7 % 5)  // 2

// 함수 활용
function isEven(num) { // isEven 함수 생성
    return num % 2 === 0
}

console.log(isEven(3)) // num 인수에 3을 대입하여 계산한 값 출력: false
console.log(isEven(4)) // num 인수에 4를 대입하여 계산한 값 출력: true

 

할당 연산자 (Assignment)

■ const: 재할당 불가능 (X)

const a = 3 // const 코드는 재할당 불가능
a = a + 2 // 연산 진행 불가

console.log(a) // 결과 출력 안됨

 

■ let: 재할당 가능 (O)

let b = 3 // let 코드는 재할당 가능
b = b + 2 // b = 3 + 2

console.log(b) // 5

▼ 더하기 할당 연산자 (+=)

// 더하기 할당 연산자
let b = 3 // let 코드는 재할당 가능
b += 2 // b = b + 2 와 동일한 코드

console.log(b) // 5

 

▼ 빼기 할당 연산자 (-=)

// 빼기 할당 연산자
let b = 3
b -= 2 // b = b - 2

console.log(b) // 1

 

그 외에도 곱하기, 나누기, 나머지 할당 연산자가 있음. (*=, /=, %=)

// 곱하기 할당 연산자 (*=)
let b = 3
b *= 2 // b = b * 2

console.log(b) // 6

// 나누기 할당 연산자 (/=)
let b = 3
b /= 2 // b = b / 2

console.log(b) // 1.5

// 나머지 할당 연산자 (%=)
let b = 3
b %= 2 // b = b % 2

console.log(b) // 1

 

증감 연산자 (Increment & Decrement)

증가 연산자(Increment): ++

  • ++ 의 위치에 따라 결과가 달라짐.
    - 출력하고자 하는 값의 뒤에 ++ 붙이는 경우 (a++): 기존의 a 변수에 선언해둔 값을 먼저 출력한 이후에 a의 값을 1 증가시켜 저장함.
    - 출력하고자 하는 값의 앞에 ++ 붙이는 경우 (++b): b 변수에 선언해둔 값을 1 증가시켜 출력하고, 1 증가된 값을 b 변수에 저장함. 
// 증가 연산자 (++)
let a = 3

console.log(a++) // 3 (기존의 a 값을 출력한 이후에, a 값을 1 증가시킴)
console.log(a)   // 4 

let b = 3
console.log(++b) // 4 (b값을 1 증가시켜서 출력)
console.log(b)   // 4

 

감소 연산자(Decrement): --

  • -- 의 위치에 따라 결과가 달라짐.
    - 출력하고자 하는 값의 뒤에 -- 붙이는 경우 (a--): 기존의 a 변수에 선언해둔 값을 먼저 출력한 이후에 a의 값을 1 감소시켜 저장함.
    - 출력하고자 하는 값의 앞에 -- 붙이는 경우 (--b): b 변수에 선언해둔 값을 1 감소시켜 출력하고, 1 감소된 값을 b 변수에 저장함. 
// 감소 연산자 (--)
let a = 3

console.log(a--) // 3
console.log(a)   // 2

let b = 3
console.log(--b) // 2
console.log(b)   // 2

부정 연산자 및 비교 연산자

부정 연산자(Negation): !

데이터의 '반대'를 Boolean 값(truthy & Falsy)으로 출력함.

// 부정 연산자(!)

// false -> true
console.log(!false) // true
console.log(!0)     // true
console.log(!!0)    // false
console.log(!!!0)   // true
console.log(!null) // true
console.log(!undefined) // true
console.log(!NaN) // true
console.log(!'') // true

// true -> false
console.log(!true) // false
console.log(!'0') // false
console.log(!{}) // false
console.log(![]) // false

 

비교 연산자(Comparison): ===, !==, >, >=, <, <= 

*** 동등 연산자(==) 및 부등 연산자(!=) 보다는 일치 연산자(===) 및 불일치 연산자(!==) 사용을 권장함.

∵ 동등/부등 연산자의 경우, 형변환된 결과로 비교하기 때문에 정확한 결과를 출력하지 못할 가능성 높기 때문임.

const a = 1
const b = 3

// 동등 연산자(==): 형변환된 결과로 비교
console.log(a == b) // false
// 부등 연산자(!=): 형변환된 결과로 비교
console.log(a != b) // true

// 일치 연산자(===)
console.log(a === b) // false
// 불일치 연산자(!==)
console.log(a !== b) // true

// Greater than 연산
console.log(a > b) // false
// Greater than or equal 연산
console.log(a >= b) // false

// Less than 연산
console.log(a < b) // true
// Less than or equal 연산
console.log(a <= b) // true

논리 연산자(Logical)

  • 그리고(AND) 연산자: &&
    - 조건문이 모두 참인 경우, 값이 출력됨.
    - 하나라도 거짓인 경우, 값은 출력되지 않음.

  • 또는(OR) 연산자: ||
    - 조건문이 적어도 하나가 참이라면, 값이 출력됨.
const a = true
const b = false

// AND (그리고) 연산자
if(a && b) {
    console.log('모두가 참!!') // 출력 X
}

// OR (또는) 연산자
if(a || b) {
    console.log('둘 중 어느 하나는 참(하나 이상)!') // 출력 O
}
// AND (그리고) 연산자
console.log(true && false) // false

// 좌측에서 우측으로 데이터를 확인하면서 false를 의미하는 데이터가 확인되면 바로 false 값에 해당하는 데이터 출력됨. 
console.log(1 && 0) // 0 (false가 되는 0이 출력됨)
console.log(1 && 2 && 0) // 0
console.log(1 && 0 && 2) // 0
console.log(0 && 1 && 2) // 0
console.log('A' && 'B' && '') // 0 (빈 문자는 0을 의미하므로 0으로 반환)
console.log('A' && 'B' && 'C') // C (문자 A, B, C 모두 true 이므로, 마지막에 확인된 C가 출력됨)
// OR (또는) 연산자
console.log(false || true) // true

// 좌측에서 우측으로 데이터를 확인하면서 true를 의미하는 데이터가 확인되면 바로 true 값에 해당하는 데이터 출력됨. 
console.log(0 || 1) // 1 
console.log(false || 0 || {}) // {}
console.log(false || [] || null) // []
console.log(function () {} || undefined || '') // f () {}
console.log(false || 0 || NaN) // NaN

Nullish 병합 및 삼항 연산자

Nullish 병합(Nullish Coalescing): ??

- 좌측에서 우측으로 데이터를 확인하면서 null, undefined 데이터만 건너뛰고, 그 외 모든 데이터를 만날 시 즉시 그 값을 반환함.

- 만약, null 과 undefined 데이터를 비교해야 하는 경우에는 마지막에 해당하는 가장 우측의 데이터를 반환함. (__ ?? __)

// Nullish 병합 연산자(??)
const n = 0
const num = n ?? 7
console.log(num) // 0

console.log(null ?? 1) // 1
console.log(undefined ?? 2) // 2
console.log(null ?? undefined) // undefined (undefined가 마지막 데이터이기 때문에, 해당 값 반환)
console.log(null ?? 1 ?? 2) // 1
console.log(false ?? 1 ?? 2) // false
console.log(0 ?? 1 ?? 2) // 0

 

삼항 연산자(Ternary): 조건 ? 참 : 거짓

조건 ?: 거짓

→ 조건이 true인 경우에는 참에 해당하는 값을 반환하고, 조건이 false인 경우에는 거짓에 해당하는 값을 반환함.

const a = 1

if (a < 2) {
    console.log('참~~!') // 참~~! 으로 출력 O
} else {
    console.log('거짓...!') // 출력 X
}

/* 삼항연산자 
   조건 ? 참 : 거짓 (조건이 참이면 참에 해당하는 값 출력, 조건이 거짓이면 거짓에 해당하는 값 출력) */
console.log(a < 2 ? '참~~!' : '거짓...!')

// 함수형 활용
function getAlert(message) {
    return message ? message : '메세지가 존재하지 않음.'
}

// message가 참이면 message 값을 그대로 출력해냄.
console.log(getAlert('안녕하세요?')) // 안녕하세요?

// 빈문자열인 경우 message는 false에 해당함.
console.log(getAlert('')) // 메세지가 존재하지 않음.

전개 연산자

전개 연산자(Spread Operator): ...

- 데이터를 펼쳐서 출력함.

- 배열 데이터에서 대괄호[]를 삭제해줌.  

const a = [1, 2, 3] // 배열 데이터
const b = [4, 5, 6] // 배열 데이터

console.log(...a) // 1 2 3
console.log(...b) // 4 5 6

const c = a.concat(b) // concat 메소드 통해 배열데이터 a에 b를 병합시킴.
console.log(c)

const d1 = [a, b] // [1, 2, 3, 4, 5, 6]
console.log(d1) // [[1, 2, 3], [4, 5, 6]]
const d2 = [...a, ...b]
console.log(d2) // [1, 2, 3, 4, 5, 6] (전개 연산자를 통해 대괄호[] 삭제해줌.)

cf. concat 메소드를 통해 데이터를 병합시킬 수 있음.

// x, y, z 라는 속성을 가진 객체 생성
const a = { x: 1, y: 2 }
const b = { y: 3, z: 4 }

// 객체 a와 b를 병합하여 새로운 객체 c 생성
const c = Object.assign({}, a, b) 

console.log(c) // {x: 1, y: 3, z: 4}

// 전개 연산자(...) 활용
const d1 = {a, b}
console.log(d1) // a: {x: 1, y: 2}, b: {y: 3, z: 4}

const d2 = {...a, ...b}
console.log(d2) // {x: 1, y: 3, z: 4}
// 함수 활용
function fn(x, y, z) {
    return console.log(x, y, z)
}

fn(1, 2, 3) // 1 2 3

// 배열 활용
const a = [1, 2, 3] // 배열 데이터 a 생성 

fn(a[0], a[1], a[2]) // 1 2 3 (a의 0번째 아이템, 1번째 아이템, 2번째 아이템 삽입) 
fn(...a) // 1 2 3

구조 분해 할당(Destructuring assignment)

- 배열 데이터객체 데이터에서만 쓰이는 방법임.

// 변수 a, b, c의 값을 0으로 선언함.
let a = 0
let b = 0
let c = 0

// arr 배열 생성 (구조 분해 할당)
const arr = [1, 2, 3]

// 동일한 구조의 배열 생성 및 변수 나열
;[a, b, c] = arr // ; 표시를 arr 배열 할당한 것 뒤에 붙여도 되고, 배열 구조 선언하는 구문 앞에 붙여도 됨. 

console.log(a, b, c) // 1 2 3

 

*** 구조 분해 할당 활용 시, 배열문에서 출력하지 않을 변수는 빈문자인 상태에서 쉼표(,)만 남겨서 표현해줌.

let a = 0
let b = 0
let c = 0
const arr = [1, 2, 3]

;[, b, c] = arr

console.log(b, c) // 2 3
let a = 0
let b = 0
let c = 0
const arr = [1, 2, 3]

;[, , c] = arr

console.log(c) // 3

 

▼ 배열 데이터 활용 예시 

const arr = [1, 2, 3]
const [a, ...rest] = arr // a = 1, rest = 2, 3 (rest는 나머지를 의미하는 임의의 변수명)

console.log(a, rest) // 1, [2, 3]

 

 객체 데이터 활용 예시

- 객체 데이터의 경우, 객체 요소 나열 시 출력하지 않을 요소는 삭제해버리고 빈문자와 쉼표 남기지 않음.

// 객체 생성
const obj = {
    a: 1,
    b: 2,
    c: 3
}

// 객체의 요소 나열
const { a, b, c } = obj
console.log(a, b, c) // 1 2 3

const { b, c } = obj
console.log(b, c) // 2 3

 

- 기본값 지정: 객체 데이터의 구조 지정 시, 객체 생성 시 선언했던 변수 및 할당된 값 이외에 추가적인 변수 선언 및 기본값 지정 가능함.

- 변수명 변경: 객체 생성 시 선언했던 변수명을 객체 데이터 구조 지정 시에 변경할 수 있음.

// 객체 생성
const obj = {
    a: 1,
    b: 2,
    c: 3,
}

// 기본값 지정, 변수명 변경 
const { 
    x = 4, // obj 객체에 선언되지 않은, 새로운 변수 x에 4라는 값 할당 (기본값 지정)
    a: JJACK, // 변수 a의 이름을 JJACK으로 변경
    y: SPARROW = 25 // obj 객체에 선언되지 않은, 새로운 변수 y의 이름을 SPARROW로 변경하고 25라는 값 할당
} = obj 

console.log(x, JJACK, SPARROW) // 4 1 25
const obj = {
    a: 1,
    b: 2,
    c: 3,
    x: 10,
    y: 25
}

// 전개 연산자(...) 활용하여 변수 c 이외의 나머지 결과(...rest) 호출
const { c, ...rest } = obj 

console.log(c, rest) // 3 {a: 1, b: 2, x: 10, y: 25}
const obj = {
    a: 1,
    b: 2,
    c: 3,
    x: 10,
    y: 25
}

// 전개연산자(...)와 rest 변수를 통해 나머지 값들을 호출함.
const { ...rest } = obj // 따로 명확히 호출한 변수값이 없기 때문에 전체 변수 호출함.

console.log(rest) // {a: 1, b: 2, c: 3, x: 10, y: 25}

선택적 체이닝(Optional Chaining)

- 점 표기법 사용 시, 점(.) 앞에 사용한 데이터가 점 표기법을 사용할 수 없는 경우에도 error 발생시키지 않고 undefined를 출력해줌.

- 주로 null, undefined 데이터에서 사용됨.

const userA = {
    name: 'JJACK',
    age: 25,
    address: {
        country: 'Germany',
        city: 'Berlin'
    }
}
const userB = {
    name: 'MARK',
    age: 24
}

function getCity(user) {
// 선택적 체이닝을 사용하여 특정 속성 데이터가 함수 내 포함되어 있지 않은 경우에도 error 발생하지 않고 undefined 출력
    return user.address?.city 
}

function getName(user) {
    return user.name
}

console.log(getCity(userA)) // Berling
console.log(getCity(userB)) // undefined
console.log(getName(userA)) // JJACK
console.log(getName(userB)) // MARK

 

▼ 논리 데이터 - OR (또는) 연산자 활용 예시

const userA = {
    name: 'JJACK',
    age: 25,
    // address 속성 안에 country, city 속성 추가
    address: {
        country: 'Germany',
        city: 'Berlin'
    }
}
const userB = {
    name: 'MARK',
    age: 24
}

function getCity(user) {
    // OR (또는) 연산자로 예외 처리
    return user.address?.city || '주소 없음'
}

console.log(getCity(userA)) // Berling
console.log(getCity(userB)) // 주소 없음

/* OR (또는) 연산자 활용
   userB의 경우 address 속성을 포함하지 않는 객체이기 때문에, 
   user.address?.city는 거짓이고 
   또는(OR) 연산자 뒤에 오는 '주소 없음'은 문자열임에 따라 참으로 간주되어 해당 값이 반환됨.
*/

If, Switch 조건문

If 조건문

  • if 문
    - 조건 1개
if (조건) { ... }

 

  • if ... else 문
    - 조건 2개
    - else 문의 경우, else 및 중괄호 { } 는 생략 가능하여 return 문만 써도 됨.
if (조건) { 
    ... 
} else {
    ...
}
  • if ... else if ... else 문
    - 조건 3개 이상
    - else 문의 경우, else 및 중괄호 { } 는 생략 가능하여 return 문만 써도 됨.
if (조건1) { 
    ... 
} else if (조건2) {
    ...
} else if (조건3) {
    ...
} else {
    ...
}

 

▼ if 조건문의 활용 예시

function isPositive(number) {
    if (number > 0) {
        return '양수'
    } else if (number < 0) {
        return '음수'
    } else {
    	return '0'
    }
}

console.log(isPositive(1)) // 양수
console.log(isPositive(0)) // 0
console.log(isPositive(-1)) // 음수
// else { return문 } 의 경우, else 및 중괄호{}는 생략 가능하여 return 문만 써도 무방함.

function isPositive(number) {
    if (number > 0) {
        return '양수'
    } else if (number < 0) {
        return '음수'
    } return '0' // *** else { } 생략
}

console.log(isPositive(1)) // 양수
console.log(isPositive(0)) // 0
console.log(isPositive(-1)) // 음수

 

Switch 조건문

* Switch 조건문은 언제든지 If 조건문으로 변환하여 사용할 수 있음.

* 반대로, if 조건문은 상황에 따라 switch 조건문으로 변환하여 사용할 수 없는 경우도 있음.

  • :
    - case 값과 default 다음에 반드시 : 기호 넣어야 함.

  • break
    - switch 문 실행 종료 시킴.

  • default 문
    - else와 동일한 기능을 함.
    - 모든 case 조건에 해당하지 않는 경우, default 문 실행됨.  

  • return 문
    - 결과값 반환 및 switch 문 종료 시켜주기 때문에, return 문 사용 시 break 작성할 필요 없음.
switch (조건) {
    case 값1:
      // 조건이 값1인 경우 실행
      break
    
    case 값2:
      // 조건이 값2인 경우 실행
      break
      
    default: // else와 동일한 기능
      // 조건이 값1, 값2 둘 다 아닐 때 실행
}

아래의 예시와 같이 조건에 해당하는 명확한 값이 있는 경우, Switch 조건문을 사용하는 것이 좀 더 직관적인 코드가 될 수 있음.

 

▼ Switch 조건문 활용 예시

- 과일(fruit)들의 가격(price)을 확인하기 위한 함수 생성하고자 함.

- 과일(fruit)에는 사과(Apple), 바나나(Banana), 체리(Cherry)가 있고, 각 과일별 가격이 책정되어 있음.

즉, 과일이라는 조건에 대한 명확한 값들(사과, 바나나, 체리)이 있기 때문에 Switch 조건문을 활용하는 것이 권장될 수 있음.

function price(fruit) {
    switch (fruit) {
        case 'Apple':
            return 1000
        case 'Banana':
            return 1500
        case 'Cherry':
            return 2000
        default:
            return 0
    }
}

console.log(price('Apple'))  // 1000
console.log(price('Banana')) // 1500
console.log(price('Cherry')) // 2000
console.log(price('Melon'))  // 0

For, For of, For in 반복문

For 반복문

for (초기화; 조건; 증감) {
    // 반복 실행할 코드
}

 

▼ For 반복문 활용 예시

for (let i = 0; i < 10; i += 1) {
    console.log(i) // 0부터 9까지의 숫자 데이터가 콘솔창에 출력됨
}

for (let j = 9; j > -1; j -= 1) {
    console.log(j) // 9부터 0까지의 숫자 데이터가 콘솔창에 출력됨
}

 

▼ For 반복문의 'break' 및 'continue' 기능 비교 

// break 활용
for (let i = 9; i > -1; i -= 1) {
    if (i < 4) {
        break
    }
    console.log(i)
}

// continue 활용
for (let j = 9; j > -1; j -= 1) {
    if (j % 2 === 0) {
        continue 
    }
    console.log(j) // 2의 배수를 제외한 값만 출력
}
/* if문의 조건에 해당하면 
현재 for 반복문이 실행되지 않고 다음 for 반복문으로 넘어가기 때문에 
console.log() 실행되지 않음. */

- break: break 키워드가 실행되면, for 반복문을 완전히 중단하고 빠져나가게 됨.

- continue: continue 키워드가 실행되면, 현재의 for 반복문을 중단하고 다음 반복으로 넘어가게 됨.

 

For of 반복문

- 'of' 를 통해 배열의 요소에 접근함.

- for 반복문 보다 좀 더 간결한 코드로 작성 가능함.

// fruits 배열 생성 
const fruits = ['Apple', 'Banana', 'Cherry']

for (let i = 0; i < fruits.length; i += 1) {
    console.log(fruits[i]) // Apple Banana Cherry 순서대로 출력
}

// fruit 변수를 생성하고 of를 통해 fruits 배열 내 요소에 접근할 수 있도록 함. 
for (const fruit of fruits) { // fruit 변수 통해 fruits 배열의 요소에 접근할 수 있게 됨.
    console.log(fruit) // Apple Banana Cherry 순서대로 출력
}
// users 배열 생성
const users = [
    {
        name: 'JJACK',
        age: 25
    }, 
    {
        name: 'MARK',
        age: 24
    }, 
    {
        name: 'TAEMIN',
        age: 28
    }
]

// for 반복문 활용
for (let i = 0; i < users.length; i += 1) {
    console.log(users[i])
}

// for of 반복문 활용
for (const user of users) {
    console.log(user)
}

 

▼ 위의 예시 코드에서 users 배열 내 속성들이 객체 데이터 { } 로 지정되어 있기 때문에, 아래와 같이 점 표기법 통해 각 속성 별로 호출 가능함.

const users = [
    {
        name: 'JJACK',
        age: 25
    }, 
    {
        name: 'MARK',
        age: 24
    }, 
    {
        name: 'TAEMIN',
        age: 28
    }
]

// for 반복문
for (let i = 0; i < users.length; i += 1) {
    console.log(users[i].name) // JJACK MARK TAEMIN
}

// for of 반복문
for (const user of users) {
    console.log(user.age) // 25 24 28
}

 

For in 반복문

- 데이터 타입 확인 가능함.

// user 객체 생성
const user = {
    name: 'JJACK',
    age: '25',
    isValid: true,
    email: 'JJACKSPARROW@gmail.com'
}

// 객체의 속성값 확인하는 방법: 객체명['...'], 객체명.속성명
console.log(user['name']) // JJACK
console.log(user.age) // 25

// for in 반복문
for (const key in user) {
    console.log(key)       // 데이터 타입 출력 
    console.log(user[key]) // 속성값 출력 
}

While 및 Do While 반복문

While 반복문

1st. 조건 확인

2nd. 구문 실행

- 조건문이 참(true)이면, { ... } 구문 반복함. 

- 조건문이 거짓(false)이면, while 문 반복 중단하고 while 문 벗어남. 

let n = 0
while (n < 4) { // n이 4미만인 경우 { } 내부 구문 반복
    console.log(n)
    n += 1
}
// n이 4 이상이면 while 문 반복 중단하고 while 문 벗어남

 

Do While 반복문

1st. 구문 실행 (*최초 1회는 무조건 실행)

2nd. 조건 확인

- do { ... } 구문 우선 실행함.

- do { ... } 구문 실행 이후에 조건 확인함. → 조건이 거짓(false)이라도, 최초 1회는 do { ... } 구문 실행함.

- do { ... } 구문 실행 이후, while (조건)에서 조건이 거짓(false)이면 do { ... } 구문 반복하지 않고 do while 문 실행 종료됨.

let n = 0

// while 문
while (n) { // n은 0이고, 0은 false를 의미함.
    console.log(n) // 출력되지 않음.
}

// do - while 문
do {
    console.log(n) // 0 
} while (n)
let n = 0

do {
    console.log(n)
    n += 1
} while (n < 4)

// 출력 결과: 0 1 2 3

'LANGUAGE > JavaScript' 카테고리의 다른 글

클래스(Class); 프로토타입(Prototype)  (0) 2023.12.26
함수  (1) 2023.12.23
Node.js 설치 시 참고사항  (0) 2023.12.21
JS 데이터  (1) 2023.12.21
DOM API (Document Object Model, Application Programming Interface)  (1) 2023.12.16