티스토리 뷰
반응형
- 종종 결과값이 있는지 없는지에 따라 true / false를 반환해야 하는 다음과 같은 경우가 있다.
- if / else 분기로 처리하는 경우 코드가 불필요하게 길어질 수 있고, 삼항연산자를 사용하면 다소 가독성이 떨어지는 경우가 있다.
async function example(id) {
const result = await getResult(id);
// result가 falsy한 경우에 false, 아닌 경우에는 true를 반환
return result ? true : false;
}
- 이는 느낌표 한개, 또는 두 개를 활용하여 축약할 수 있다.
- 해당 방식은 result가 falsy한 경우 !(result)에 의해 true가 되며, !(느낌표)를 하나 더 붙여 false로 바꾸어주는 결과를 낳는다.
async function example(id) {
const result = await getResult(id);
// result가 falsy한 경우에 false, 아닌 경우에는 true를 반환
return !!(result);
}
- falsy한 값과 그렇지 않은 값을 예시로 테스트한 결과는 다음과 같다.
const all = {
i_am_null: null,
i_am_undefined: undefined,
i_am_false: false,
i_am_0: 0,
i_am_arr: [],
i_am_obj: {},
i_am_1: 1,
i_am_true: true,
};
for (const target in all) {
console.log(`--- test ---`);
console.log(`${target} with ! : `, !(all[target]));
console.log(`${target} with !!: `, !!(all[target]));
}
/* 실행 결과
--- test ---
i_am_null with ! : true
i_am_null with !!: false
--- test ---
i_am_undefined with ! : true
i_am_undefined with !!: false
--- test ---
i_am_false with ! : true
i_am_false with !!: false
--- test ---
i_am_0 with ! : true
i_am_0 with !!: false
--- test ---
i_am_arr with ! : false
i_am_arr with !!: true
--- test ---
i_am_obj with ! : false
i_am_obj with !!: true
--- test ---
i_am_1 with ! : false
i_am_1 with !!: true
--- test ---
i_am_true with ! : false
i_am_true with !!: true
*/
- null, undefined, false, 0 등 falsy한 값은 !로 인해 true가 되고, !!로 인해 false가 되는 것을 확인할 수 있다.
- falsy하지 않는 [], {}, 1, true는 반대의 결과가 나타난다.
- 사실 삼항연산자를 썼었는데, WebStorm한테 코드를 단순화하라고 혼났다.
'Dev. > javascript' 카테고리의 다른 글
[JS] 두 배열을 하나의 오브젝트로 합치기 (0) | 2021.11.05 |
---|---|
[JS] 배열을 map으로 변환하기 (0) | 2021.09.15 |
[JS] optional chaining (0) | 2021.08.10 |
[JS] nullish coalescing operator (널 병합 연산자) (0) | 2021.08.10 |
[JS] javascript engine 참고 (0) | 2021.07.05 |
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- hashicorp
- eureka
- Node.js
- Java
- etc
- react
- pgloader
- Puppeteer
- JPA
- spring boot
- mysql
- RancherDesktop
- kotlin
- terraform
- AWS IoT
- IntelliJ
- Linux
- Database
- Spring Cloud Config
- AWS
- shell
- Gradle
- Docker
- jQuery
- Vault
- Git
- postgresql
- JEST
- 코딩테스트
- javascript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함