02. Truthy and Falsy
Truthy and Falsy
μ΄κ²μ μλ°μ€ν¬λ¦½νΈ λ¬Έλ²κΉμ§λ μλμ§λ§, μμλ¬μΌ νλ κ°λ μ λλ€. Truthy: true κ°μκ±°... Falsy: false κ°μκ±°... λΌκ³ μ΄ν΄λ₯Ό νλ©΄ λλλ°μ, μλ₯Ό λ€μ΄μ λ€μκ³Ό κ°μ ν¨μκ° μλ€κ³ κ°μ ν΄λ΄ μλ€.
function print(person) {
console.log(person.name);
}
const person = {
name: 'John'
};
print(person);
λ§μ½μ μ΄λ¬ν μν©μμ, λ§μ½ print
ν¨μκ° λ€μκ³Ό κ°μ΄ νλΌλ―Έν°κ° λΉμ΄μ§ μ±λ‘ μ€νλλ€κ³ κ°μ ν΄λ΄
μλ€.
function print(person) {
console.log(person.name);
}
const person = {
name: 'John'
};
print();
μ΄ μ½λλ λ€μκ³Ό κ°μ μλ¬λ₯Ό μμ±ν΄λ λλ€.
TypeError: Cannot read property 'name' of undefined
μ΄λ¬ν μν©μμ, λ§μ½μ print
ν¨μμμ λ§μ½μ object
κ° μ£Όμ΄μ§μ§ μμλ€λ©΄, λ¬Έμ κ° μλ€κ³ μ½μμ μΆλ ₯ν΄μΌ νλ€λ©΄ λ€μκ³Ό κ°μ΄ ꡬν ν μ μμ΅λλ€.
function print(person) {
if (person === undefined) {
return;
}
console.log(person.name);
}
const person = {
name: 'John'
};
print();
κ·Έλ°λ° λ§μ½μ λ€μκ³Ό κ°μ΄ print
μ null
κ°μ΄ νλΌλ―Έν°λ‘ μ λ¬λλ©΄ μ΄λ¨κΉμ?
function print(person) {
if (person === undefined) {
console.log('personμ΄ μλ€μ');
return;
}
console.log(person.name);
}
const person = null;
print(person);
κ·Έλ¬λ©΄ λ μ€λ₯κ° λ°μνκ² λ©λλ€.
TypeError: Cannot read property 'name' of null
κ·Έλ¬λ©΄ λ.. print ν¨μμ 쑰건μ μΆκ°ν΄μ€μΌν©λλ€.
function print(person) {
if (person === undefined || person === null) {
console.log('personμ΄ μλ€μ');
return;
}
console.log(person.name);
}
const person = null;
print(person);
μ΄λ κ² person μ΄ undefined μ΄κ±°λ, null μΈ μν©μ λλΉνλ €λ©΄ μμ κ°μ΄ μ½λλ₯Ό μμ±ν΄μΌνλλ°μ, μ¬κΈ°μ μ μ½λλ λ€μκ³Ό κ°μ΄ μΆμ½ν΄μ μμ± ν μ μλ΅λλ€.
function print(person) {
if (!person) { // μΆμ½ν΄μ μμ± ν μ½λ
console.log('personμ΄ μλ€μ');
return;
}
console.log(person.name);
}
const person = null;
print(person);
μ΄κ² μλνλ μ΄μ λ, undefined μ null μ κΈ°λ³Έμ μΌ Falsy ν κ°μ λλ€. Falsy ν κ° μμ λλνλ₯Ό λΆμ¬μ£Όλ©΄ true λ‘μ νλ©λλ€.
λ€μ μ½λλ₯Ό μ λ ₯ν΄λ³΄μΈμ.
console.log(!undefined); //true
console.log(!null); //true
Falsyκ° μ’
λ₯λ€
Falsy ν κ° 5κ° μμ΅λλ€.
console.log(!undefined); //true
console.log(!null); //true
console.log(!0); //true
console.log(!''); //true
console.log(!NaN); //true
μ΄ κ°μ λͺ¨λ true κ° λ©λλ€.
Falsy ν κ°μ μ λμ΄ν λ€μ―κ°μ§ μ λλ€.! κ·Έλ¦¬κ³ , κ·Έ μΈμ λͺ¨λ κ°μ Truthy ν κ°μ λλ€.
Truthyκ° μ’
λ₯λ€
console.log(!3); //false
console.log(!'hello'); //false
console.log(!['array']); //false
console.log(![]); //false
console.log(!{ }); //false
μ΄λ²μλ μκΉμλ λ°λλ‘ λͺ¨λ κ°μ΄ false κ° λ©λλ€.
μΆκ°μ μΌλ‘, μμλλ©΄ μ μ©ν ν νλλ₯Ό λλ¦¬κ² μ΅λλ€. λ§μ½μ, νΉμ κ°μ΄ Truthy ν κ°μ΄λΌλ©΄ true, κ·Έλ μ§ μλ€λ©΄ false λ‘ κ°μ νννλ κ²μ ꡬνν΄λ³΄κ² μ΅λλ€.
const value = { a: 1 };
const truthy = value ? true : false;
μ΄μ μ λ°°μ΄ μΌνμ°μ°μλ₯Ό μ¬μ©νλ©΄ μ½κ² value κ°μ μ‘΄μ¬ μ¬μ λ°λΌ μ½κ² true λ° false λ‘ μ νμ΄ κ°λ₯ν©λλ€. κ·Έλ°λ°, μ΄λ₯Ό λ μ½κ² ν μλ μμ΅λλ€.
const value = { a: 1 };
const truthy = !!value;
console.log(truthy) //true
!value λ false κ° λκ³ , μ¬κΈ°μ !false λ true κ° λμ΄μ, κ²°κ³Όλ true κ° λ©λλ€.
Last updated
Was this helpful?