티스토리 뷰
Truthy, Falsy이란?
JavaScript에서는 참과 거짓인 boolean 타입이 아닌 값들로 참과 거짓을 평가한다. 아래 예제를 통해 알아보았다.
Falsy 값 종류
// Falsy 값. 아래 7가지가 있다.
let falsy1 = undefined;
let falsy2 = null;
let falsy3 = 0;
let falsy4 = -0;
let falsy5 = NaN;
let falsy6 = ""; // 공백은 Truthy 값이다.
let falsy7 = 0n;
if (falsy1) {
console.log("Falsy 값이 아니다.");
} else {
console.log("Falsy 값이다.");
}
위의 코드에서 Falsy 값은 7가지가 있다. 그외는 전부 Truthy 값이다.
Truthy 값 종류
// Truthy 값 종류 앞서 Falsy 값을 제외한 나머지
let truthy1 = "123";
let truthy2 = 123;
let truthy3 = -1;
let truthy4 = " ";
let truthy5 = [1, 2, 3];
let truthy6 = [NaN];
let truthy7 = {};
if (truthy1) {
console.log("Truthy 값이다.");
} else {
console.log("Truthy 값이 아니다.");
}
위의 코드에서 Truthy 값은 앞서 7가지의 Falsy 값들을 제외한 나머지 값들이다.
Truthy, Falsy 활용
function printName(person) {
if (!person) {
console.log("pserson 값이 없음.");
return;
}
console.log(person.name);
}
let person = { name: "면목동인간" };
// let person = null;
printName(person);
위의 코드에서 함수 매개 변수에 객체를 넘겨 줬는데 객체 값으로 true, false로 평가하여 함수를 구현하였다. 이렇게 JavaScript의 boolean 타입이 아닌 값들로도 조건절을 구현할 수 있다.
정리
JavaScript에서는 boolean 타입이 아닌 나머지(true, false 외) 값들로도 조건절과 같은 boolean 타입이 필요한 곳에서 다양하게 구현할 수 있다.
본 포스팅은 “[2024] 한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지 편/인프런”를 학습한 내용을 정리한 것
댓글
