Frontend/Javascript
[JS] 병합 연산자 (nullish coalescing operator) 사용 방법
밤토리아이티
2023. 5. 13. 16:33
728x90
병합 연산자란 null이나 undefined를 체크하고자 할때 사용한다.
현업에서 null이나 undefined 체크를 할때 나의 경우는 or연산자를 많이 써서 체크했었다.
하지만 숫자 0의 경우는 false로 구분하기에 자칫 실수를 할 수도 있다.
ES11 문법에서 추가된 내용으로 병합 연산자를 소개하고자 한다.
첫째로 아래와 같이 변수들을 정의해 보았다.
const isZero = 0;
const isNull = null;
const isUndefined = undefined;
const isEmpty = '';
1. OR 연산자를 쓸 경우
//# OR 연산자
const orCode1 = isZero || 'this is [Null] or [Undefined]';
const orCode2 = isNull || 'this is [Null] or [Undefined]';
const orCode3 = isUndefined || 'this is [Null] or [Undefined]';
const orCode4 = isEmpty || 'this is [Null] or [Undefined]';
console.log(`orCode1 : ${orCode1}`); // 숫자 0 을 false로 인식함
console.log(`orCode2 : ${orCode2}`);
console.log(`orCode3 : ${orCode3}`);
console.log(`orCode4 : ${orCode4}`);
위와 같이 0의 경우 false로 인식하여 undefined로 정의가 된다.
2. 병합 연산자로 쓸 경우
//# 병합 연산자
const cleanCode1 = isZero ?? 'this is [Null] or [Undefined]';
const cleanCode2 = isNull ?? 'this is [Null] or [Undefined]';
const cleanCode3 = isUndefined ?? 'this is [Null] or [Undefined]';
const cleanCode4 = isEmpty ?? 'this is [Null] or [Undefined]';
console.log(`cleanCode1 : ${cleanCode1}`);
console.log(`cleanCode2 : ${cleanCode2}`);
console.log(`cleanCode3 : ${cleanCode3}`);
console.log(`cleanCode4 : ${cleanCode4}`);
위와 같이 undefined와 null을 제대로 구분할 수 있다.
728x90