IT공간/JavaScript

Truthy와 Falsy

dkchae 2022. 5. 16. 13:13

Falsy는 null, undefined, 0, '', NaN 이 다섯가지를 뜻한다.
Truthy는 Falsy가 아닌 것이니 !Falsy다.

console.log(!null); // true
console.log(!undefined); // true
console.log(!0); // true
console.log(!''); // true
console.log(!NaN); // true

아래와 같이 truthy, falsy에 대한 검증을 할 수 있다.

let value = "트루티한 abc";
console.log(value || "출력값은 falsy 입니다."); // "트루티한 abc"
    
value = null;
console.log(value || "출력값은 falsy 입니다."); // "출력값은 falsy 입니다."

JSON 키 값이 없거나 falsy할 때 아래와 같이 적용할 수 있다.

const person = { };
if(!person.name) person.name = 'unknown';