티스토리 뷰
반응형
참고
Nullish coalescing operator - JavaScript | MDN
널 병합 연산자 (??) 는 왼쪽 피연산자가 null 또는 undefined일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자이다.
developer.mozilla.org
요약
- 표기 : var_A ?? var_B
- 의미: var_A가 nullish한 값(null 또는 undefined)인 경우 var_B를 반환하고, 그렇지 않은 경우 var_A를 반환한다.
- 때문에 || (OR) 연산자와는 차별점이 있다. OR 연산자는 falsy한 값에 대해 모두 반응하기 때문이다.
??와 || 비교
- nullish한 값과 초기화된 변수에 대해서는 같은 동작을 보인다.
const i_am_null = null;
const i_am_undefined = undefined;
const i_am_value = 'monkey';
console.log('?? nullish test: ', i_am_null ?? 'ingnoh');
console.log('|| nullish test: ', i_am_null || 'ingnoh');
console.log('?? undefined test: ', i_am_undefined ?? 'ingnoh');
console.log('|| undefined test: ', i_am_undefined || 'ingnoh');
console.log('?? value test: ', i_am_value ?? 'ingnoh');
console.log('|| value test: ', i_am_value || 'ingnoh');
/* 실행결과
?? nullish test: ingnoh
|| nullish test: ingnoh
?? undefined test: ingnoh
|| undefined test: ingnoh
?? value test: monkey
|| value test: monkey
*/
- 그러나 false, 0, 빈 문자열과 같은 falsy한 값에 대해서는 다른 동작을 보인다.
let i_am_falsy = 0;
console.log('?? falsy test: ', i_am_falsy ?? 'ingnoh');
console.log('|| falsy test: ', i_am_falsy || 'ingnoh');
i_am_falsy = false;
console.log('?? falsy test: ', i_am_falsy ?? 'ingnoh');
console.log('|| falsy test: ', i_am_falsy || 'ingnoh');
i_am_falsy = '';
console.log('?? falsy test: ', i_am_falsy ?? 'ingnoh');
console.log('|| falsy test: ', i_am_falsy || 'ingnoh');
/* 실행결과
?? falsy test: 0
|| falsy test: ingnoh
?? falsy test: false
|| falsy test: ingnoh
?? falsy test:
|| falsy test: ingnoh
*/
주의사항
'Dev. > javascript' 카테고리의 다른 글
[JS] 느낌표 두개 (2) | 2021.09.10 |
---|---|
[JS] optional chaining (0) | 2021.08.10 |
[JS] javascript engine 참고 (0) | 2021.07.05 |
[JS] curry, currying (커리, 커링) (0) | 2021.06.23 |
[JS] Promise의 이해 (0) | 2021.06.10 |
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- JEST
- jQuery
- Database
- JPA
- react
- Node.js
- IntelliJ
- Vault
- postgresql
- Git
- hashicorp
- Java
- Puppeteer
- AWS IoT
- terraform
- Docker
- RancherDesktop
- Gradle
- Linux
- AWS
- shell
- pgloader
- etc
- 코딩테스트
- eureka
- Spring Cloud Config
- spring boot
- kotlin
- javascript
- mysql
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함