JavaScript

Javascript์—์„œ false๋กœ ๊ฐ„์ฃผ๋˜๋Š” ๊ฒƒ๋“ค(์•Œ์•„๋‘๋ฉด ์œ ์šฉํ•œ ์ •๋ณด)

martinooo 2022. 12. 13. 14:37

๐Ÿคฆ‍โ™€๏ธ Javascript ๊ณต๋ถ€์ „์— ์•Œ๋ฉด ์ข‹์€๊ฒƒ


์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” ๋‘ ๊ฐ€์ง€ ์ข…๋ฅ˜์˜ ๊ฐ’์ด ์žˆ๋‹ค.

ํ•˜๋‚˜๋Š” Primitive Value(์›์‹œ๊ฐ’)์ด๊ณ , ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” Reference Value(์ฐธ์กฐ๊ฐ’)์ž…๋‹ˆ๋‹ค.

 

  • ์›์‹œ๊ฐ’: number, string, boolean, null, undefined
  • ์ฐธ์กฐ๊ฐ’: array, function, object 

๐Ÿคณ Javascript ์—์„œ boolen ๊ฒฐ๊ณผ๊ฐ€ false๋กœ ํŒ๋ช…๋˜๋Š” ๊ฒƒ๋“ค์€?


  • undefined, null
  • NaN
  • 0, -0
  • " "
  • false

๋‹ค์Œ๊ณผ ๊ฐ™์ด 7๊ฐ€์ง€ ์ •๋„์˜ boolen ๊ฒฐ๊ณผ๊ฐ’์€ false๋กœ ํŒ๋ช…์ด ๋œ๋‹ค.


๐Ÿคณ ์ฃผ์˜ํ• ์ ?


์ฃผ์˜ํ•  ์ ์€ ๋นˆ ๋ฌธ์ž์—ด์€ false ์ด์ง€๋งŒ ๋นˆ ๋ฐฐ์—ด, ๋นˆ ๊ฐ์ฒด๋Š” true๋ผ๋Š” ๊ฒƒ์ด๋‹ค.

> Boolean( "" )
false

> Boolean( [] )
true

> Boolean( {} )
true

NaN์€ ๊ทธ์ž์‹ ๊ณผ ๊ฐ™์ง€ ์•Š๋Š” ์œ ์ผํ•œ ์ž๋ฃŒํ˜•์ด๋‹ค.

> undefined == undefined
true

> null == null
true

> NaN == NaN
false

๐Ÿคณ ์ข‹์€ ์˜ˆ์ œ!


const result = 1; //1์€ boolean true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
if(result) console.log('true ๋กœ์ง ๊ตฌํ˜„')

const result2 = 0; // 0์€ boolean false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
if(!result2) console.log('false ๋กœ์ง ๊ตฌํ˜„')

๐Ÿคท‍โ™‚๏ธ == ์—ฐ์‚ฐ์—์„œ์˜ ํ˜•๋ณ€ํ™˜


๋‹ค๋ฅธ ํƒ€์ž…์„ ๊ฐ€์ง„ ๋‘ ๊ฐ’์ด ๊ฐ™์€์ง€ ๋น„๊ตํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹น์—ฐํžˆ ํ˜•๋ณ€ํ™˜์ด ์„ ํ–‰์œผ๋กœ ์ด๋ค„์ ธ์•ผํ•œ๋‹ค. === ์—ฐ์‚ฐ์ž๋Š” ํ˜•๋ณ€ํ™˜์„ ๋ฐœ์ƒ์‹œํ‚ค์ง€ ์•Š๋Š”๋‹ค. ๋ฐ˜๋ฉด์— == ์—ฐ์‚ฐ์ž๋Š” ํ˜•๋ณ€ํ™˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค. 

if (1 == '1') console.log('true')

if (0 == '') console.log('true')

 

๋ฌธ์ž์—ด๊ณผ ์ˆซ์ž์˜ == ์—ฐ์‚ฐ์€ ๋ฌธ์ž์—ด์ด ์ˆซ์ž๋กœ ํ˜•๋ณ€ํ™˜๋œ๋‹ค.