Javascript
null 병합 연산자
안자바먹지
2020. 11. 11. 16:33
728x90
옵셔널 체이닝 연산자와 마찬가지로 ES11에 도입되었다.
연산자 ?? 는 좌항의 피연산자가 null 또는 undefined일 경우 우항의 피연산자를 반환하고, 그렇지 않으면 좌항의 피연산자를 반환한다. 변수에 기본값을 설정할 때 유용하다.
병합연산자 ?? 가 도입되기 전에는 논리연산자 || 를 통한 단축평가로 기본값을 설정하였다.
// null 병합 연산자 사용
let testString = null ?? 'this is test string';
console.log(testString); // "this is test string"
// || 단축 연산자 사용
let testString = '' || 'this is test string';
console.log(testString); // "this is test string"
하지만 옵셔널 체이닝 연산자와 마찬가지로 좌항의 피연산자가 Falsy한 값이라도 null 또는 undefined가 아니면 좌항의 피연산자를 그대로 반환한다.
let testString = '' ?? 'this is test string';
console.log(testString); // ""
728x90