Nullish coalescing assignment (??=)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2020ë 9ì.
ë ë³í© í ë¹ ì°ì°ì(??=) ëë ë
¼ë¦¬ì ë í ë¹ì ì¼ìª½ í¼ì°ì°ìê° nullish(null ëë undefined)ì¼ ë, ì¤ë¥¸ìª½ í¼ì°ì°ì를 íê°íì¬ ì¼ìª½ì í ë¹í©ëë¤.
ìëí´ ë³´ê¸°
const a = { duration: 50 };
a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
a.duration ??= 10;
console.log(a.duration);
// Expected output: 50
구문
x ??= y
ì¤ëª
ë ë³í© í ë¹ì short-circuitsì ìíí©ëë¤.
ì¦, x ??= y ë x ?? (x = y)ì ê°ì§ë§ xë ì¤ì§ í ë²ë§ íê°ë©ëë¤.
ì¼ìª½ í¼ì°ì°ìê° nullish (null ëë undefined)ê° ìë ê²½ì°, í ë¹ì ìíëì§ ììµëë¤. ì를 ë¤ì´, ìë ì½ëììë x ê° constë¡ ì ì¸ëììë ë¶êµ¬íê³ ìë¬ë¥¼ ë°ììí¤ì§ ììµëë¤.
const x = 1;
x ??= 2;
ìë ì½ëììë setter í¨ìë í¸ì¶ëì§ ììµëë¤.
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ??= 2;
ì¤ì ë¡, x ê° nullishê° ìë ê²½ì° yë íê°ì¡°ì°¨ ëì§ ììµëë¤.
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing
ìì
>ë ë³í© í ë¹ ì¬ì©í기
ë ë³í© í ë¹ ì°ì°ì(??=)를 ì¬ì©íì¬ ê°ì²´ ìì±ì 기본 ê°ì ì ì©í ì ììµëë¤.
구조 ë¶í´ í ë¹ê³¼ 기본 ê°ì ì¬ì©íë ë°©ìê³¼ë ë¤ë¥´ê², ìì± ê°ì´ nullish (null ëë undefined)ì¸ ê²½ì°ìë 기본 ê°ì ì§ì í ì ììµëë¤.
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
ëª ì¸ì
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-assignment-operators> |