[JavaScript] Null, Undefined ํธ๋ค๋ง: Optional Chaining ์ฐ์ฐ์
Optional Chaining ์ฐ์ฐ์ (?.) ES11 (ECMAScript 2020)
๊ฐ์ฒด์ Property์ ์ ๊ทผํ๊ฑฐ๋ ํจ์๋ฅผ ํธ์ถํ์ ๋
undefined ๋๋ null์ธ ๊ฒฝ์ฐ
์๋ฌ๋ฅผ ๋์ง๋ ๋์ , undefined๋ฅผ ๋ฐํํ๋ค.
์ฆ, nullish๊ฐ (null ๋๋ undefined) ์ผ๋ก ์ธํด ์๋ฌ๊ฐ ๋ฐ์ํ๋ ๊ฒ์ ๊ฐ๋จํ ํํ์ผ๋ก ์ฒ๋ฆฌํ ์ ์๋ค.
์ Optional Chaining์ ์ฌ์ฉํ ๊น?
์๋ฅผ ๋ค์ด adventurer ๊ฐ์ฒด ์์ ์ค์ฒฉ๋(nested) cat ๊ฐ์ฒด๊ฐ ์๋ ์๋์ ์ฝ๋๋ฅผ ๋ณด์.
nullish ๊ฐ์ ์ฒดํฌํ๋ฉด์(null ๋๋ undefined์ธ ๊ฒฝ์ฐ ์๋ฌ๊ฐ ๋ฐ์ํ๊ธฐ ๋๋ฌธ)
adventurer ๊ฐ์ฒด์ ์ค์ฒฉ๋ 'cat ๊ฐ์ฒด์ name'์ ๊ฐ์ ธ์ค๋ ค๋ฉด ์ด๋ป๊ฒ ํ ์ ์์๊น?
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
1๏ธโฃ ์๋์ ๊ฐ์ด && ์ฐ์ฐ์ ์ด์ฉํด cat์ด null ๋๋ undefined์ธ์ง ์ฒดํฌํ๊ณ , cat.name์ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ
const catName = adventurer && adventurer.cat && adventurer.cat.name;
2๏ธโฃ Optional Chaining ์ด์ฉ
const catName = adventurer?.cat?.name;
์ ๋๊ฐ์ง ๋ฐฉ๋ฒ์ ๋น๊ตํด๋ณด๋ฉด Optional Chaining์ด ์ ์ฐ์ด๋์ง ์ ์ ์๋ค.
๋งค์ฐ ์งง๊ณ , ๊ฐ๋จํ๊ฒ Chaining์ ํตํด null ๋๋ undefined์ ๋ํ ํธ๋ค๋ง์ด ๊ฐ๋ฅํ๋ค!
ํนํ, ๊ฐ์ฒด์ ์ด๋ค property๊ฐ ์๊ตฌ๋๋์ง, ์กด์ฌํ๋์ง์ ๋ํด guarantee ๋์ด์์ง ์์ ๊ฒฝ์ฐ(null ๋๋ undefined ๊ฐ๋ฅ์ฑ์ด ์๋ ๊ฒฝ์ฐ) ํด๋น property์ ์ ๊ทผํ ๋ ์ ์ฉํ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
Syntax
obj.val?.prop
obj.val?.[expr]
obj.func?.(args)
์ฐธ๊ณ ์ถ์ฒ: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining