Front End/Javascript

[ Javascript ] null 병합 연산자 '??' 와 논리연산자 '||' 의 차이점

YJ_SW 2023. 3. 2. 20:04
728x90

null 병합 연산자 '??' (Nullish coalescing operator)

널 병합 연산자는 만약 왼쪽 표현식이 null 또는 undefined 인 경우, 오른쪽 표현식의 결과를 반환한다.

let name;
...
//  name assign된적 없고, undefined의 값
let text = name ?? 'Hello!';

// 결과
console.log(text) // Hello!

 

논리연산자 ' || ' 

null 또는 undefined 뿐만 아니라 falsy 값 ( 0 , '' , NaN )에 해당할 경우 오른쪽 피연산자를 반환

null병합연산자 '??'와의 차이점은 falsy 값도 유효하지 않은 값으로 처리하여 오른쪽 피연산자를 반환한다는 것이다.

let num;
let text;
...
num = 0;
text = "";
...
// 논리연산자 '||' 는 0, "" false값으로 취급
let logicalNum = num || 100;
let logicalText = text || "hello!";
console.log(logicalNum);     // 100 
console.log(logicalText); // "hello!"

// null병합연산자 '??' 는 0, "" 유효한값으로 취급
let nullishNum = num ?? 100;
let nullishText = text ?? "hello!"
console.log(nullishNum);     // 0 
console.log(nullishText); // ""
  • 논리연산자 '||' 는 0, "", NaN을  false 값으로 취급
  • null병합연산자 '??' 는 0,"",NaN을 유효한 값으로 취급

0, '', NaN, 이를 유효한 값으로 생각한다면 ?? 연산자를 사용해야 한다.

 

728x90