nullish 병합 연산자(nullish coalescing operator) ??를 사용하면 짧은 문법으로 여러 피연산자 중 그 값이 '확정되어있는'변수를 찾을 수 있다.
a ?? b의 평가 결과
x = (a !== null && a !== undefined) ? a : b;
// null이나 undefined가 아닌 첫 번째 피연산자
console.log(firstName ?? lastName ?? nickName ?? "익명의 사용자"); // 바이올렛
let height = 0;
console.log(height || 100); // 100
console.log(height ?? 100); // 0
let height = null;
let width = null;
// 괄호를 추가!
let area = (height ?? 100) * (width ?? 50);
console.log(area); // 5000
let x = 1 && 2 ?? 3; // '&&' 및 '??' 작업은 괄호 없이 혼합해서 사용할 수 없습니다.ts(5076)
let x = (1 && 2) ?? 3; // 제대로 동작합니다.
javascript.info 사이트에서 공부한 내용 정리