[javaScript] Truthy & Falsy

728x90

 

- javaScript에서는 참, 거짓이 아닌 값도 참, 거짓으로 평가함

→ if(123) 넣으면 true로 판단 if(undefined) 는 false로 판단 

이러한 특징을 Truthy (참같은 값) & Falsy (거짓같은 값) 이라고 한다.

 

1. Falsy한 값

let f1 = undefined;
let f2 = null;
let f3 = 0;
let f4 = -0;
let f5 = NaN;
let f6 = "";
let f7 = 0n; //0n은 big Integer 라는 특수한 자료형

if(!f1) console.log("falsy");

 

2. Truthy한 값

- Falsy한 값을 제외한 모든 값

let t1 = "hello"; //비어있지 않은 문자열 
let t2 = 123; //0이 아닌 숮자 
let t3 = []; //빈 배열이나 객체, 함수 등 
let t4 = {};
let t5 = () => {};

 

3. Truthy & Falsy 활용

function printName(person){
    console.log(person.name);
}

let person = {name :"홍길동"};
printName(person);

위의 코드에서 let pserson ; 으로 가정하여 undefined가 된 경우 error가 발생함

이 때 null이나 undefined를 체크함. 이 때 Truthy & Falsy 를 이용하지 않고 아래와 같이 검증하는 경우

function printName(person){
    if(person === undefined)    console.log(person.name); //null은 체크되지 않음 
}
let person ;
printName(person);

null이 체크되지 않거나 undefined가 체크되지 않는 상황이 발생함

function printName(person){
    if(!person) console.log(person.name);
}
let person ;
printName(person);

하지만 위와 같이 코드를 작성하는 경우 null, undefined을 한번에 체크 할 수 있음

 

728x90