본문 바로가기
JavaScript

[JavaScript] ??(널 병합)연산자와 ?.(옵셔널 체이닝)연산자

by 잘노는 주인장 2023. 11. 9.

ES2020에서 추가된 ??(널 병합)연산자?.(옵셔널 체이닝)연산자에 대해 공부해보자!

 

널 병합 연산자 ( ?? )

널 병합 연산자는 주로 || 연산자 대용으로 사용되며, falsy 값 (0, '', false, NaN, null, undefined) 중 null 과 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 = null;
const h = g ?? 3; 
console.log(h); // 3

 

 

 

옵셔널 체이닝 연산자 ( ?. )

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

 

const a = {};
a.b; // a가 객체이므로 문제 없음

const c = null;
try{
	c.d;
} catch (e) {
	console.log(error(e)); // TypeError: Cannot read properties of null (reading 'd')
}
c?.d; //문제없음


try{
	c.f();
} catch (e) {
	console.log(error(e)); // TypeError: Cannot read properties of null (reading 'f')
}
c?.f(); //문제없음


try{
	c[0];
} catch (e) {
	console.log(error(e)); // TypeError: Cannot read properties of null (reading '0')
}
c?.[0]; //문제없음

 

 

 

 

 

널병합연산자와 옵셔널 체이닝 연산자를 사용하면 if문과 같은 코드를 많이 줄일 수 있어서 적극 권장한다!!

'JavaScript' 카테고리의 다른 글

[JavaScript] WeakMap/WeakSet  (1) 2023.11.08
[JavaScript] Map/Set  (0) 2023.11.08
[JavaScript] onClick, addEventListener 이벤트 비교  (0) 2023.09.30
[JavaScript] Ajax  (0) 2023.09.18
[JavaScript] indexOf - 특정 문자(요소) 위치 찾기  (1) 2023.09.03