Web Dev/1. JS 문법 관련
Nullish coalescing operator (??) 사용법
hYhY1234
2021. 1. 26. 22:02
728x90
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This can be contrasted with the logical OR (||) oper
developer.mozilla.org
nullish coalescing operator (??) 은 논리 연산자이다.
class Foo {
name;
constructor(public rawName?: string){
this.name = rawName ?? '(no name)'
}
log(){
console.log(this.name)
}
}
예를들어 이렇게 쓰인다. 이름이 없을때(null, undefined) `(no name)` 을 반환하는 것이다.
이걸 || 와 혼돈 할 수 있는데, 이건 falsy value 에도 적용이 되서 위의 경우에 || operator를 사용하면 이름이 "" 이런값이 들어와도 (no name)을 반환하게 된다