Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is double question mark equal? [duplicate]

Tags:

javascript

What does ??= do in JavaScript?

keys.reduce((o, k) => o[k] ??= {}, obj)[last] = value
like image 328
Bhojendra Rauniyar Avatar asked Sep 07 '25 02:09

Bhojendra Rauniyar


1 Answers

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

like image 99
Bhojendra Rauniyar Avatar answered Sep 08 '25 16:09

Bhojendra Rauniyar