nullish ๋ณํฉ์ฐ์ฐ์ ??
์ต๊ทผ์ ์ถ๊ฐ๋จ.
์คํ์ ์ถ๊ฐ๋์ง ์ผ๋ง์๋ ๋ฌธ๋ฒ. ๊ตฌ์ ๋ธ๋ผ์ฐ์ ๋ ํด๋ฆฌํ์ด ํ์ํ๋ค.
nullsh ๋ณํฉ์ฐ์ฐ์(nullish coalescing operator) ??
๋ฅผ ์ฌ์ฉํ๋ฉด ์งง์ ๋ฌธ๋ฒ์ผ๋ก ์ฌ๋ฌ ํผ์ฐ์ฐ์ ์ค ๊ทธ ๊ฐ์ด ํ์ ๋์ด ์๋ ๋ณ์๋ฅผ ์ฐพ์ ์ ์๋ค.
a ?? b
์ ํ๊ฐ ๊ฒฐ๊ณผ๋ ๋ค์๊ณผ ๊ฐ๋ค.
a
๊ฐnull
๋ ์๋๊ณundefined
๋ ์๋๋ฉดa
- ๊ทธ ์ธ์ ๊ฒฝ์ฐ
b
nullish ๋ณํฉ ์ฐ์ฐ์ ??
์์ด x = a ?? b
์ ๋์ผํ ๋์์ ํ๋ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.
x = (a !== null && a !== undefined) ? a : b;
??
์ ||
์ ์ฐจ์ด
||
๋ ์ฒซ ๋ฒ์งธ truthy๊ฐ์ ๋ฐํ.??
๋ ์ฒซ ๋ฒ์งธ ์ ์๋(defined) ๊ฐ์ ๋ฐํ.null
๊ณผundefined
, ์ซ์0
์ ๊ตฌ๋ถ์ง์ด ๋ค๋ค์ผ ํ ๋ ๋งค์ฐ ์ค์.
// height์ ๊ฐ์ด ์ ์๋์ง ์์ ๊ฒฝ์ฐ height์ 100์ด ํ ๋น.
height = hegiht ?? 100;
let height = 0;
alert(height || 100);
alert(height ?? 100);
height || 100
์ height
์ 0
์ falsy(0 = false
)ํ ๊ฐ์ผ๋ก ์ทจ๊ธ, null
์ด๋ undefined
๋ฅผ ํ ๋นํ ๊ฐ์ผ๋ก ์ทจ๊ธ. 100
์ ๊ฒฐ๊ณผ๋ฅผ ๋ณ๋๋ค.
๋ฐ๋ฉด, height ?? 100
์ ํ๊ฐ๊ฒฐ๊ณผ๋ height
๊ฐ ์ ํํ๊ฒ null
์ด๋ undefined
์ผ ๊ฒฝ์ฐ์๋ง 100
์ด ๋๋ค. 0
์ ๊ฒฐ๊ณผ๊ฐ์ด ๋์จ๋ค.
??
๋ ๋ณ์์ ๊ธฐ๋ณธ๊ฐใ ๋ฅด ํ ๋นํ๋ ์ฉ๋๋ก ์ฌ์ฉํ ์ ์๋ค.
// height๊ฐ null์ด๋ undefined์ธ ๊ฒฝ์ฐ, 100์ ํ ๋น.
height = height ?? 100;
์ฐ์ฐ์ ์ฐ์ ์์
??
์ ์ฐ์ฐ์ ์ฐ์ ์์๋ ๋๋ค์์ ์ฐ์ฐ์๋ณด๋ค ๋ฎ๊ณ?
์=
๋ณด๋ค๋ ๋๋ค.- ๊ดํธ์์ด
??
๋ฅผ||
๋&&
์ ํจ๊ป ์ฌ์ฉํ๋ ๊ฒ์ ๊ธ์ง๋์ด ์๋ค.
Reference
'๐ฉ๐ปโ๐ปSTUDY > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] ์ฐธ์กฐ์ ์ํ ๊ฐ์ฒด ๋ณต์ฌ (0) | 2022.01.25 |
---|---|
[JavaScript] ๊ฐ์ฒด (0) | 2022.01.24 |
[JavaScript] return์ด ํ๋ ์ผ (0) | 2021.11.26 |
[JS] script async/defer (0) | 2021.10.22 |
[JavaScript / ES6] let, const์ ๋ธ๋ก ๋ ๋ฒจ ์ค์ฝํ (0) | 2021.02.11 |