๐Ÿฆœ Computer Language/JavaScript

[JavaScript] Truthy & Falsy

Truthy: ์ฐธ์ด ์•„๋‹ˆ๋ผ ์ฐธ๊ฐ™์€ ๊ฐ’

Falsy: ๊ฑฐ์ง“์ด ์•„๋‹ˆ๋ผ ๊ฑฐ์ง“๊ฐ™์€ ๊ฐ’

 

์ด๊ฒŒ ๋ฌด์Šจ ์†Œ๋ฆฌ์ธ๊ฐ€

 

์˜ˆ์‹œ๋ฅผ ๋ณด์ž

 

Truthy ex:

  • {} ๋นˆ ๊ฐ์ฒด
  • [] ๋นˆ ๋ฐฐ์—ด
  • 0์„ ์ œ์™ธ ํ•œ ์ˆซ์ž๊ฐ’
  • ๋นˆ ๋ฌธ์ž์—ด์„ ์ œ์™ธํ•œ ๋ฌธ์ž์—ด

Falsy ex:

  • null
  • defined
  • 0
  • ๋นˆ ๋ฌธ์ž์—ด
  • NaN

์˜ˆ์‹œ๋ฅผ ๋ณด๋‹ˆ๊น ๊ฐ์ด ์˜จ๋‹ค.

ํŒŒ์ด์ฌ์—์„œ๋„ ๋นˆ ๋ฐฐ์—ด์ธ์ง€ ํ™•์ธํ•  ๋•Œ

# python
arr = []
if not arr:
    print("๋นˆ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.")
else:
    print("๋นˆ ๋ฐฐ์—ด์ด ์•„๋‹™๋‹ˆ๋‹ค.")

์œ„ ์˜ˆ์‹œ์ฒ˜๋Ÿผ arr๋ฅผ true/false๋กœ ๋ฐ˜ํ™˜ํ•˜์—ฌ ํŒ๋‹จํ•˜๋Š”๋ฐ, ์ด๋Ÿฐ ๊ฑธ truthy/falsy๋ผ๊ณ  ํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

 

์œ„์˜ Python ์˜ˆ์‹œ๋ฅผ JavaScript๋กœ ๋ฐ”๊ฟ”๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

# JavaScript

const arr = []
if (!arr) {
    console.log("๋นˆ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.")
}else{
    console.log("๋นˆ ๋ฐฐ์—ด์ด ์•„๋‹™๋‹ˆ๋‹ค.")
}

 

๊ทธ๋ ‡๋‹ค๋ฉด ์ด Truthy์™€ Falsy๋ฅผ ์–ด๋–ป๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ?

 

 

const getGender = (person) => {
	return person.gender;
};

let person = { name: "Jedi", gender: "Female" };
const gender = getGender(person);

console.log(gender);

์—ฌ๊ธฐ์„œ getGender ํ•จ์ˆ˜๋Š” ๊ฐ์ฒด๋ฅผ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋ฐ›๊ณ , Gender ํ”„๋กœํผํ‹ฐ๋ฅผ return ๋ฐ›๋Š” ํ•จ์ˆ˜์ด๋‹ค. 

 

์ด ๋•Œ, person์ด undefined๋กœ ์ „๋‹ฌ๋œ๋‹ค๋ฉด?

๋‹น์—ฐํ•˜๊ฒŒ๋„, undefined๋Š” ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— person.gender๋กœ ์ ‘๊ทผ์„ ํ•  ์ˆ˜ ์—†์–ด Error๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

์ด๋Ÿฌํ•œ ์ƒํ™ฉ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•œ ํ•ด๊ฒฐ์ฑ…์œผ๋กœ Falsy๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

const getGender = (person) => {
	if (!person) {
    	return "๊ฐ์ฒด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.";
    }
    
	return person.gender;
};

let person = undefined;
const gender = getGender(person);

console.log(gender); // ๊ฐ์ฒด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.

person์— undefined/null์„ ๋Œ€์ž…ํ•˜๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋˜๊ณ  Error ๋Œ€์‹  ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ๋ฌธ์žฅ์ด ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.