널병합/옵셔널 체이닝

널 병합(??) 연산자와 옵셔널 체이닝(?.) 연산자가 ES2020에서 추가되었다.

널 병합 연산자

널 병합 연산자는 주로 || 연산자 대용으로 사용되며, falsy 값 (0, ”, false, NaN, null, undefined) 중 nulll과 undefined만 따로 구분한다.

const a = 0;
const b = a || 3; // || 연산자는 falsy 값이면 뒤로 넘어감
console.log(b); // 3
 
const c = 0;
const d = c ?? 3; // ?? 연산자는 null과 undefined일 때만 뒤로 넘어감
console.log(d); // 0
 
const e = null;
const f = e ?? 3;
console.log(f); // 3
 
const g = 0;
const h = g ?? 3;
console.log(h); // 3

옵셔널 체이닝 연산자

옵셔널 체이닝 연산자는 null이나 undefined의 속성을 조회하는 경우 에러가 발생하는 것을 막는다.

const a = {};
a.b; // a가 객체이므로 문제 x
 
// 속성 요소 접근
const c = null;
try {
  c.d;
} catch (e) {
  console.log(e); // TypeError: Cannot read properties of null (reading 'd')
}
// 옵셔널 체이닝 연산자
c?.d; // 문제 x (undefined)
 
// 함수 호출
try {
c.f();
} catch (e) {
  console.error(e): // TypeError: Cannot read properties of null (reading 'f')
}
// 옵셔널 체이닝 연산자
c?.f(); // 문제 x (undefined)
 
// 배열 요소 접근
try {
  c[0];
} catch (e) {
  console.error(e); // TypeError: Cannot read properties of null (reading '0')
}
// 옵셔널 체이닝 연산자
c?.[0]; // 문제 x (undefined)

위 코드처럼 일반적인 속성뿐만 아니라 함수 호출이나 배열 요소 접근에 대해서도 에러가 발생하는 것을 방지할 수 있다.

c?.d와 c?.f(), c?.[0]의 값은 undefined가 된다.

옵셔널 체이닝 연산자는 자바스크립트 프로그래밍을 할 때 발생하는 TypeError: Cannot read properties of undefined 또는 null 에러의 발생 빈도를 획기적으로 낮출 수 있기에 자주 사용한다.