Nullish coalescing operator ??
TypeScript 3.7 부터 지원되는 논리연산자이다.
짧은 문법으로 여러 피연산자 중 그 값이 '확정되어있는' 변수를 찾을 수 있다.
왼쪽 피연산자가 null 이나 undefined 일 때, 오른쪽 피연산자를 return 한다.
<예시 코드>
function printText(text) {
const printText = text ?? 'noText';
console.log(printText);
}
printText('Hellow World');
printText(null);
printText(undefined);
printText(false);
printText(0);
<실행결과>
실행 결과와 같이 null과 undefiend의 경우에만 오른쪽 피연산자로 출력된다.
Nullish coalescing operator ?? / Logical OR operator || 차이점
두 연산자는 유사하지만 아래의 차이점이 있다.
- ?? null, undefined 의 경우 오른쪽 코드 실행
- || falsy인 경우 오른쪽 코드 실행
<예시 코드>
function printText(text) {
const printText = text || 'noText';
console.log(printText);
}
printText('Hellow World');
printText(null);
printText(undefined);
printText(false);
printText(0);
<실행결과>
위 실행 결과와 같이 || 는 null, undefiend 뿐 아니라 false 까지 체크한다.
falsy
falsy에 해당하는 값들
- false
- undefiend, null
- 0, -0
- "", ''
leftExpr ?? rightExpr
expression 으로 함수의 결과도 연산 가능하다.
const afterExerc = getInitialState() ?? getProtein(); //proteinSupply
function getInitialState() {
return null;
}
function getProtein() {
return 'proteinSupply';
}
No chaiing with And or Or operators
null || undefined ?? "foo"; // raises a SyntaxError
?? 연산자는 AND(&&)와 OR(||) 연산자와 직접 같이 사용하는 것은 불가능하다.
(null || undefined) ?? "foo"; // returns "foo"
소괄호와 함께 사용 가능하다.
Reference
- https://im-developer.tistory.com/192
- https://www.youtube.com/watch?v=BUAhpB3FmS4
- https://ko.javascript.info/nullish-coalescing-operator
'JavaScript' 카테고리의 다른 글
[javascript] 화살표 함수(Arrow Function) (0) | 2021.09.24 |
---|---|
[javascript] 템플릿 리터럴 (Template Literal) (0) | 2021.09.23 |
[javascript] Optional Chaining '?.' (0) | 2021.09.23 |
[Javascript] 전개구문(spread syntax) (0) | 2021.09.05 |
[Javascript] 구조 분해 할당 (Object destructuring) (0) | 2021.08.05 |