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?