JavaScript
[JavaScript][기초] Truthy & Falsy
개발새발
2024. 6. 23. 20:09
반응형
Truthy & Falsy Boolean 타입이 아니더라도, 조건문 내에서 참 거짓으로 평가되는 것을 말하며
Truthy, Falsy를 사용하면 조건문을 간결하게 만들 수 있다.
// 1. Falsy한 값
let falsy1 = undefined;
let falsy2 = null;
let falsy3 = 0;
let falsy4 = -0;
let falsy5 = NaN; // Not a Number
let falsy6 = "";
let falsy7 = 0n; // BigInteger
// => 조건문에서 거짓으로 평가 됨
if (!falsy1) {
console.log(falsy1, "is false");
}
// 2. Truthy한 값
let truthy1 = "hello";
let truthy2 = 123;
let truthy3 = [];
let truthy4 = {};
let truthy5 = () => {};
let truthy6 = 123n; // BigInteger
// => 조건문에서 참으로 평가 됨
if (truthy6) {
console.log(truthy6, "is true");
}
// 3. 활용
function printNameNotCheckFalsy(person) {
console.log(person.name);
}
function printName(person) {
if (person && person.name) {
console.log(person.name);
}
}
let person; /* = {
name: "DY",
};*/
// name이 없기 때문에 오류 발생
printNameNotCheckFalsy(person); // TypeError: Cannot read properties of undefined (reading 'name')
// person.name이 falthy이기 때문에 아무 출력 없이 함수 종료
printName(person);
반응형