쌓고 쌓다

[JavaScript] 널 병합/옵셔널 체이닝 본문

프로그래밍/JavaScript

[JavaScript] 널 병합/옵셔널 체이닝

승민아 2023. 1. 24. 00:43

널 병합 연산자(??)

왼쪽 피 연산자가 null 또는 undefined일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는

논리연산자이다.

 

falsy 값 (0, '', false, NaN, null, undefined)일 경우 오른쪽 피연산자를 반환하는 논리 연산자 OR(||)와는 대조된다.

 

|| 연산자는 falsy 값이면 뒤로 넘어감.

const a = 0;
const b = a || 3;
console.log(b)
// output : 3

 

?? 연산자는 null과 undefined일 때만 뒤로 넘어감.

const a = 0;
const b = a ?? 3;
console.log(b)
// output : 0

 

const e = null;
const f = e ?? 3;
console.log(f)
// output : 3

const g = undefined;
const h = g ?? 3;
console.log(h)
// output : 3

 

옵셔널 체이닝(?.)

null이나 undefined의 속성을 조회하는 경우 에러가 발생하는 것을 막는다.

만약 결과가 null이나 undefined인 경우 undefined를 반환한다.

 

const a = {}
console.log(a.b)
// output : undefined

a가 객체이기에 문제가 되지 않는다.

 

const c = null
try {
console.log(c.d)
} catch (e) {
    console.log(e) // TypeError: Cannot read properties of null (reading 'd')
}

c가 null이기에 에러가 발생한다. 이때 옵셔널 체이닝으로 문제 없이 돌아가게 해 보자.

 

일반적인 속성의 경우

 

const c = null
c?.d

에러 없이 안전하게 접근할 수 있다.

?.은 ?. '앞' 평가 대상이 null이나 undefined이면 평가를 멈추고 undefined를 반환한다,

 

메소드의 경우

const c = null
try {
    c.f()
} catch (e) {
    console.log(e) // TypeError: Cannot read properties of null (reading 'f')
}

 

const c = null
c?.f() // 문제 없다.

c?.f()의 결과로 undefined를 반환한다.

 

배열 요소에 대한 접근의 경우

const c = null
try {
    c[0]
} catch (e) {
    console.log(e) // TypeError: Cannot read properties of null (reading '0')
}

 

const c = null
c?.[0] // 문제 없음.

 

 

*c?.d와 c?.f(), c?.[0]의 값은 undefined가 되며,

옵셔널 체이닝 연산자는 자바스크립트 프로그래밍을 할 때 발생하는

TypeError : Cannot read properties of undefined 또는 null 에러의 발생 빈도를 낮출 수 있다.

Comments