์ฐ์ฐํ ๋ณด๊ฒ๋
?. / ??.. ์ง์ง ๋ฌผ์ํ ๊ทธ ์ก์ฑ๐ค
์ต์ ๋ ์ฒด์ด๋(Optional Chaining) ์ ์๋ฐ์คํฌ๋ฆฝํธ(JavaScript)์์ ์ค์ฒฉ๋ ๊ฐ์ฒด์์ ํ๋กํผํฐ์ ์ ๊ทผํ ๋, ํด๋น ํ๋กํผํฐ๊ฐ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ ๋ฐ์ํ๋ ์ค๋ฅ๋ฅผ ๋ฐฉ์งํ๊ณ ์์ ํ๊ฒ undefined ๊ฐ์ ๋ฐํํ๋๋ก ํ๋ ์ฐ์ฐ์์ด๋ค.
โ ๊ธฐ๋ณธ ๋ฌธ๋ฒ
| ํํ | ์๋ฏธ |
|---|---|
obj?.prop | obj๊ฐ ์กด์ฌํ๋ฉด prop ๋ฐํ |
obj?.method() | obj๊ฐ ์กด์ฌํ๋ฉด method() ์คํ |
arr?.[index] | ๋ฐฐ์ด์ด ์กด์ฌํ๋ฉด ํด๋น ์ธ๋ฑ์ค ์ ๊ทผ |
ex)
const user = {
name: "Aki",
address: {
city: "Seoul",
zip: "12345"
}
};
console.log(user.address.city); // โ
"Seoul"
console.log(user.contact.email); // โ ์๋ฌ
์ ์ด๋ฏธ์ง์ฒ๋ผ user.contact.email ์๋ ๊ฐ์ฒด๋ฅผ ๋ถ๋ฌ์ฌ ๊ฒฝ์ฐ, ์๋ฌ๊ฐ ๋จ๊ฒ ๋๋ค.
์์๊ฐ ๋จ์ํด์ ๊ทธ๋ ์ง ๊ฐ์ฒด๊ฐ ์ค์ฒฉ๋์ด์๊ณ ์์ค๋ ๊ธธ๋ค๋ฉด ์ด์ฒ๋ผ ๊ฐํน ์๋ ๊ฐ์ฒด๋ฅผ ๋ถ๋ฌ์ค๋ ์ค์๋ฅผ ํ ๋๊ฐ ์..์๋ค.
์ด๋ด ๋ Optional Chaining์ ์ฌ์ฉํ๋ฉด ์๋ฌ๋์ undefined ๊ฐ์ ๋ฐํํ ์ ์๋ค.
console.log(user.address?.city); // โ
"Seoul"
console.log(user.contact?.email); // โ
undefined (์๋ฌ โ)
โจ์ด์ฒ๋ผ Optional Chaining์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ๋จผ์ ํ์ธํ ํ ์์ฑ์ด๋ ๋ฉ์๋์ ์ ๊ทผํ ์ ์๊ฒ ํด์ฃผ๊ธฐ๋๋ฌธ์ ์๋ฌ๋ฅผ ๋ง๊ณ ์ฝ๋๊ฐ ๋ ์์ ํ๊ฒ ์คํ๋๊ฒ ๋์์ค๋ค.
๐ ์ถ๊ฐ๋ก... Null ๋ณํฉ ์ฐ์ฐ์ ๊ฐ์ด ์ฌ์ฉํ๊ธฐ!
๊ฐ์ด null ๋๋ undefined์ธ ๊ฒฝ์ฐ์๋ง ๋์ฒด๊ฐ(default) ์ ์ ๊ณตํ๋ ์ฐ์ฐ์์ด๋ค.
const result = value ?? defaultValue;
value๊ฐ null ๋๋ undefined๋ผ๋ฉด defaultValue๋ฅผ ๋ฐํ
๊ทธ ์ธ์ falsy ๊ฐ(0, '', false ๋ฑ)์ ๊ทธ๋๋ก ์ ์งํจ
falsy ๊ฐ์ด๋? Boolean ๋ฌธ๋งฅ์์ false ๋ก ํ๊ฐ๋๋ ๊ฐ
ex)
const name = null;
const displayName = name ?? "Anonymous";
console.log(displayName); // "Anonymous"
// โจname๊ฐ์ด null์ด๊ธฐ๋๋ฌธ์ ๋์ฒด๊ฐ "Anonymous" ์ ๊ณต
const age = 0;
const userAge = age ?? 18;
console.log(userAge); // โ
0 (0์ falsy์ง๋ง null/undefined๊ฐ ์๋)
// โจnull/undefined๊ฐ ์๋๊ธฐ๋๋ฌธ์ falsy๊ฐ ๊ทธ๋๋ก ์ ์ง
const comment = '';
const userComment = comment ?? 'No comment';
console.log(userComment); // โ
'' (๋น ๋ฌธ์์ด ์ ์ง)
// โจnull/undefined๊ฐ ์๋๊ธฐ๋๋ฌธ์ ๋น ๋ฌธ์์ด ๊ทธ๋๋ก ์ ์ง
๋ ์กฐํฉ์ ๋ง์ด ์ฌ์ฉํ๋ ํธ
ex)
const user = {
profile: {
nickname: null
}
};
const nickname = user.profile?.nickname ?? "Guest";
console.log(nickname); // "Guest"
// โจuser.profile?.nickname์ด null์ด๋ผ์ "Guest" ๋ฐํ
์์ ์ฒซ ์์๋ก ์ ์ฉํด๋ณด๋ฉด๐
const user = {
name: "Aki",
address: {
city: "Seoul",
zip: "12345"
}
};
console.log(user.address?.city ?? "city none"); // โ
"Seoul"
console.log(user.contact?.email ?? "email none"); // โ
"email none"
// โจuser.contact?.email ๊ฐ์ด undefined ์ด๊ธฐ๋๋ฌธ์ "email none" ๋ฐํ
๐์์ฝ
| ๊ตฌ๋ฌธ | ์ค๋ช |
|---|---|
?. | ์์ ํ๊ฒ ์ ๊ทผ (์๋ฌ ๋ฐฉ์ง) |
?? | ๊ฐ์ด ์์ ๋ ๊ธฐ๋ณธ๊ฐ ์ค์ (null, undefined์ผ ๋๋ง ์๋) |