# 널 병합 연산자란?
- 왼쪽 피연산자가 null 또는 undefined일때 오른쪽 피연산자를 반환.
- 왼쪽 피연산자가 null 또는 undefined이 아니면 왼쪽 피연산자를 반환하는 '논리 연산자'
# 논리 연산자 OR과의 차이점
논리 연산자 OR (||) : 왼쪽 연산자가 null 또는 undefined 뿐만 아니라 falsy값('' 또는 0 등)에 해당할 경우 오른쪽 피연산자를 반환.
const foo = null ?? 'default string';
console.log(foo); // 'default string'
const baz = 0 ?? 42;
console.log(bas); // 0
const result = 0 || 42;
console.log(result); // 42
# 특징
- OR과 AND같은 논리 연산자들과 마찬가지로, 만약 왼쪽이 null 또는 undefined이 아님이 판명되면 오른쪽 표현식은 평가되지 않는다.
function A(){
console.log('A was called');
return undefined;
}
function B(){
console.log('B was called');
return false;
}
function C(){
console.log('C was called');
return 'foo';
}
console.log(A() ?? C());
// 'A was called' 'C was called' 'foo';
console.log(B() ?? C());
// 'B was called' false;
// 왼쪽 B()이 false이므로 null Ehsms undefined이 아님이 팡면되었다.
// 그래서 오른쪽 표현식은 평가되지 않는다.
참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
'JavaScript' 카테고리의 다른 글
[JavaScript] 옵셔널 체이닝 (?.) (0) | 2023.10.27 |
---|---|
[JavaScript] 논리적 AND 연산자 (&&) (0) | 2023.10.26 |
표현식과 문 (0) | 2023.09.21 |
스코프 의미, 규칙 및 종류 (2) | 2023.09.18 |
화살표 함수의 this (0) | 2023.09.15 |