18

What does ??= do in JavaScript?

keys.reduce((o, k) => o[k] ??= {}, obj)[last] = value
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

1 Answers1

23

??= is similar to Nullish Coalescing Operator introduced as Logical nullish assignment implemented like other languages: php example. The logical nullish assignment is introduced in ES12 (ECMAScript 2022).

The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).

Example:

let foo = null;
let bar = "Give me a beer!";

foo ??= bar;

foo ?? (foo = bar) is the equivalent of the above expression. The variable foo gets assigned the variable bar only if foo is null or undefined. In this example, foo becomes "Give me a beer!". If we replace let foo = null with `let foo = "I don't need a beer!", the assignment does not happen. The variable foo stays "I don't need a beer!".

The equivalent code with an if statement is as follows:

let foo = null;
let bar = "Give me a beer!";

if (foo == null || foo == undefined) {
    foo = bar;
}

It does not check for other falsy values. It only checks for null and undefined.


So, in your example of code o[k] assigns an empty object {} when o[k] value results null or undefined.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231