What Is Double Question Mark Equal? [Duplicate]

What does ??= do in JavaScript?

keys.reduce((o, k) => o[k] ??= {}, obj)[last] = value
2

??= 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.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest