๐Ÿ‘ฉ‍๐Ÿ’ป/JavaScript

[ES2020] Nullish Coalescing Operator (null ๋ณ‘ํ•ฉ ์—ฐ์‚ฐ์ž ??)

ํ•œ๋‚˜ 2021. 2. 24. 17:15

๊ธฐ์กด || ์—ฐ์‚ฐ์ž์˜ ํ•œ๊ณ„์ 

function isEnabled(options) {
    return console.log(options.enabled || true)
}

isEnabled({}); // true
isEnabled({enabled: null}); // true
isEnabled({enabled: false}); // true ์†์„ฑ ๊ฐ’์ธ false๋ฅผ ์ธ์‹ํ•˜์ง€ ๋ชปํ•˜๊ณ  true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋‹ค. 

|| ์—ฐ์‚ฐ์ž๋Š” ์ขŒํ•ญ์ด falsyํ•œ ๊ฒฝ์šฐ ๋ฌด์กฐ๊ฑด ์šฐํ•ญ์„ ํƒํ•œ๋‹ค. ํ•˜์ง€๋งŒ, ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” null, undefined๋ฟ ์•„๋‹ˆ๋ผ false, 0, "", NaN ๋“ฑ ๋‹ค์–‘ํ•œ ๊ฐ’์„ falsyํ•˜๊ฒŒ ์—ฌ๊ธด๋‹ค.
๋˜ํ•œ || ์—ฐ์‚ฐ์ž๋Š” ์ฒซ ๋ฒˆ์งธ truthy ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค๋ฉด(์กด์žฌํ•  ๊ฒฝ์šฐ), ??๋Š” ์ฒซ ๋ฒˆ์งธ defined value๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

??, Nullish Coalescing Operator

์—ฌ๋Ÿฌ ํ”ผ์—ฐ์‚ฐ์ž ์ค‘ ๊ฐ’์ด ํ™•์ •๋œ, ์ฆ‰ null๋„ ์•„๋‹ˆ๊ณ  undefined๋„ ์•„๋‹Œ ๊ฒฝ์šฐ๋ฅผ ํ‰๊ฐ€ํ•œ๋‹ค.

x = (a !== null && n !== undefined) ? a : b; // ์ด ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋Š” ์•„๋ž˜์™€ ๋™์ผํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋‚ธ๋‹ค. 

x = (a ?? b)
let firstName = null;
let lastName = null;
let nickName = 'developer';

console.log(firstName ?? lastName ?? nickName ?? 'Anonymous'); // developer
let hight = 0;
console.log(height || 100); // 100. 0์„ falsy ๊ฐ’์œผ๋กœ ์ทจ๊ธ‰. ๋”ฐ๋ผ์„œ null, undefined๋ฅผ ํ• ๋‹นํ•œ ๊ฒƒ๊ณผ ๋™์ผํ•˜๊ฒŒ ์ฒ˜๋ฆฌ
console.log(height ?? 100); // 0. height๊ฐ€ ์ •ํ™•ํžˆ null์ด๋‚˜ undefined์ผ ๊ฒฝ์šฐ์—๋งŒ 100 

Node.js 14 ์ด์ƒ๋ถ€ํ„ฐ ์ง€์›

ํ„ฐ๋ฏธ๋„์—์„œ node.js ์ƒ์—์„œ๋Š” ??์„ ์ธ์‹ํ•˜์ง€ ๋ชปํ•˜๊ธธ๋ž˜ ์ฐพ์•„๋ณด๋‹ˆ 14๋ถ€ํ„ฐ ์ง€์›ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค. ์œˆ๋„์šฐ์˜ ๊ฒฝ์šฐ์—๋Š” ์ง์ ‘ ํ™ˆํŽ˜์ด์ง€์— ๊ฐ€์„œ ๋‹ค์šด ๋ฐ›์•„ ์—…๋ฐ์ดํŠธ๋ฅผ ์ง„ํ–‰ํ•ด์•ผ ํ–ˆ๋‹ค.

Tips

  • 0์ด ํ• ๋‹น๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š” ๊ธฐ๋Šฅ ๊ฐœ๋ฐœ ์‹œ์—๋Š” ?? ์„ || ๋Œ€์‹  ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค.

  • ์—ฐ์‚ฐ์ž ์šฐ์„ ์ˆœ์œ„ 5๋กœ ๋‚ฎ์œผ๋ฏ€๋กœ ์‚ฌ์šฉ ์‹œ ๊ด„ํ˜ธ๋ฅผ ์ ์ ˆํžˆ ๋ฌถ์–ด ์‚ฌ์šฉํ•œ๋‹ค.

  • ??๋Š” &&์ด๋‚˜ ||์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜์ง€ ๋ชปํ•œ๋‹ค. -> ๊ด„ํ˜ธ๋กœ ๋ฌถ์–ด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ES2020์— ๋„์ž…๋œ ?. ์—ฐ์‚ฐ์ž์™€ ํ•จ๊ป˜ ์“ธ์ˆ˜๋ก ๋ง‰๊ฐ•ํ•ด์ง„๋‹ค.

์ฐธ๊ณ 

www.daleseo.com/js-nullish-coalescing/

ko.javascript.info/nullish-coalescing-operator