?.옵셔널 체이닝 연산자는, 좌항의 피연산자가 null 또는 undefined 라면 undefined 를 반환하고,
그렇지 않다면 연산자의 우항을 참조한다.
const elem = null;
const value = 5;
console.log(elem?.value);
// undefined
elem 이 null 이기 때문에 value 는, 좌항에서 끝나고 그대로 undefined 를 출력한다.null 또는 undefined 임을 확인할때 사용할 수 있다.if (elem === undefined) {
console.log(undefined);
} else {
console.log(value);
}
const elem = true;
const value = 1;
console.log(!elem?.value);
// 이렇게 하면 true일때 value를 출력한다.
undefined 가 아니라는 조건도 쓸 수 있다.??null 병합 연산자는, 좌항의 피연산자가 null 또는 undefined 라면 우항의 값 반환하고,
그렇지 않다면 좌항의 값을 반환한다.
const foo = null ?? `str`;
console.log(foo);
// str
null 또는 undefined 이므로 우항의 값인 str 을 반환한다.null 또는 undefined 인지 확인할 수 있기 때문이다.&& , || 연산자가 생각나기도 한다.