출처: 한 입 크기로 잘라먹는 리액트
// Truthy & Falsy
if (123) {
console.log("123 is true"); // 출력 Truthy 한 값 (참 같은 값)
} else {
console.log("!23 is false");
}
if (undefined) {
console.log("undefined is true");
} else {
console.log("undefined is false") // 출력 Falsy 한 값 (거짓 같은 값)
}
// Javascript에 모든 값은 Truthy 하거나 Falsy 하다.
// 이를 이용하면 조건문을 간결하게 만들 수 있다.
// 1. Falsy 한 값
let f1 = undefined;
let f2 = null
let f3 = 0;
let f4 = -0;
let f5 = NaN;
let f6 = "";
let f7 = 0n // 7가지의 값은 조건문에서 false로 평가됨
if (!f1) {
console.log('falsy'); // falsy;
}
// 2. Truthy 한 값
// 7가지 Falsy 한 값들 제외한 나머지 모든 값
let t1 = 'hello';
let t2 = 123;
let t3 = [];
let t4 = {};
let t5 = () => {};
// 3. 활용 사례
function printName(person) {
if (!person) {
console.log("person의 값이 없음") // person 매개 변수의 값이 null이나 undefined가 들어왔을 떄, false + false = true로 변환되면서,
return; // 조건문이 실행되는 원리. 참조하고자 하는 객체의 값이 정확히 들어있는지 확인하기 위한 용도
} // 이렇게 비효율적인 조건문을 줄일 수 있다. 이렇게 안하면 7가지의 경우의수를 모두 고려해서 ||로 이어나가게 됨
console.log(person.name);
}
let person = null;
printName(person);