JS: Logical Assignment Operators (??= ||= &&=)

By Xah Lee. Date: . Last updated: .

new in ECMAScript 2021

Logical-nullish assignment operator

x ??= val

Assigns val to x if x is null or undefined .

let xx;
// if xx is null or undefined, give it a value
xx ??= 4;
console.assert(xx === 4);

Logical-or assignment operator

x ||= val

Assigns val to x if Boolean(x) eval to false. [see JS: Boolean. true false]

let xx = 0;
xx ||= 4;
console.assert(xx === 4);

let yy = 1;
yy ||= 4;
console.assert(yy === 1);

Logical-and assignment operator

x &&= val

Assigns val to x if Boolean(x) eval to true. [see JS: Boolean. true false]

let xx = 3;
xx &&= 4;
console.assert(xx === 4);
let x;
x &&= 4;
console.assert(x === undefined);