Falsy의 종류

charlie_·2021년 8월 1일

TIL

목록 보기
42/42
post-thumbnail

Falsy는 크게 5가지가 있다. 이외에는 모두 true다.

1) 문자열 공백
let test = "";
console.log(!test) // true
2) 0
let test = 0;
console.log(!test) // true
3) undefined
let test = undefined;
console.log(!test) // true
4) null
let test = null;
console.log(!test) // true
5) NaN
let test = "hi"/0;
console.log(!test) // true

하.지.만. 오늘 궁금한 건 이미 알고 있는 falsy에 대한 것이 아니었다. 만약 배열이 비어있으면 true일까 false일까? 빈 객체는? 빈 배열에 빈 문자열만 있으면?

궁금해서 해봤다.

객체와 배열이 비었을 때

let array = [];
let obj = {};
console.log(!array) // false
console.log(!obj) // false

배열에 undefined만 들어있을 때

let array = [undefined];
console.log(!array) // false

배열에 NaN만 들어있을 때

let array = ["hi"/2];
console.log(!array) // false

배열에 null만 들어있을 때

let array = [null];
console.log(!array) // false

오늘의 결론: 배열과 객체는 무조건 true다

profile
매일 하루에 딱 한 걸음만

0개의 댓글