Fall in IT.

JavaScript null 병합 연산자 '??'에 대하여 본문

프로그래밍언어/Javascript & Typescript

JavaScript null 병합 연산자 '??'에 대하여

D.Y 2021. 11. 27. 13:04

안녕하세요.

오늘은 JavaScript에서 유용하게 사용되는 null 병합 연산자(nullish coalescing operator)에 대하여 알아보겠습니다.

 

null 병합 연산자(nullish coalescing operator)란?

짧은 문법으로 여러 피연산자 중 값이 확정되어 있는 변수를 쉽게 찾을 수 있도록 도와주는 연산자이다.

 

예제 1

변수 a와 b가 있을때 a가 null이나 undefined가 아니면 a를 그 외의 경우는 b를 대입하는 경우를 생각해보자

// null 병합 연산자 사용 안했을경우
let result = (a !== null && a!== undefined) ? a : b

// or

let result = a ? a : b

// null 병합 연산자 사용한 경우
let result = a ?? b

 

OR연산자('||')와 null 병합 연산자(??)의 차이는?

 

  • OR 연산자는 첫 번째 truthy 값을 반환한다.
  • null 병합 연산자는 첫 번째 defined 값을 반환한다. 

 

예제2

// '||'와 '??' 의 차이

let height = 0;
let result = height || 100;
let result2 = height ?? 100;

console.log(result); //  Output: 100
console.log(result2); // Output: 0

이런 특징 때문에 0이 할당 될 수 있는 변수를 사용해 기능을 개발할 땐 '||' 보단 '??'가 적합하다.

 

참조

https://ko.javascript.info/nullish-coalescing-operator

 

Comments