a ?? b
- a 가 null, undefined가 아니면 a
- 그 외는 b
- 첫 번째 정의된(defined) 값을 반환한다.
// 1. nullish operator 사용
x = a ?? b;
// 2. 1과 동일한 동작
x = (a === undefined || a === null) ? a : b;
false
인 경우가 아니라 정의되지 않았을 때 (null 혹은 undefined)
b를 반환한다.let height = 0;
console.log(height || 100); // 100
// heigh의 값은 0으로 false 정의된 변수임
console.log(height ?? 100); // 0
??
의 연산자 우선순위는 대다수의 연산자보다 낮고 ?와 = 보다는 높다.let height = null;
let width = null;
let area = height ?? 100 * width ?? 50;
console.log(area); // NaN
??
연산자의 우선 순위가 *
보다 낮기 때문에 100 * width
가 먼저 실행된다.height ?? (100 * width) ?? 50
let height = null;
let width = null;
let area = (height ?? 100) * (width ?? 50);
console.log(area); // 5000
??
는 &&
나 ||
와 함께 사용할 수 없다. (1&&2) ?? 3
);