JS: Logical Assignment Operators

By Xah Lee. Date: .

new in JS2021

LOGICAL Nullish assignment operator

x ??= y
  • Assigns y to x if x is null or undefined .
  • left-hand-side must be assignable, such as a variable or property.

typically used for assigning a value to a object property but only when the property does not exist. 〔see Get Set Property

let x;
// if x has no value (null or undefined), give it one
x ??= 4;
console.log(x === 4);
let x = false;
// if x has no value (null or undefined), give it one
x ??= 4;
console.log((x === 4) === false);
// assignment failed, because x do have a value already

LOGICAL OR assignment operator

x ||= y

left-hand-side must be assignable, such as a variable or property.

typically used for assigning a value to a object property but only when the property does not exist or has no “valid” value (e.g. false, null or undefined). 〔see Get Set Property

let xx = 0;
// if xx eval to false, give it a new value
xx ||= 4;
console.log(xx === 4);

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

LOGICAL AND assignment operator

x &&= y
  • Assigns y to x if Boolean(x) eval to true. 〔see JS: Boolean. true false
  • left-hand-side must be assignable, such as a variable or property.
let x = 3;
x &&= 4;
// assignment successful, because x eval to true
console.log(x === 4);
let x;
x &&= 4;
// assignment fails because x was false
console.log(x === undefined);

JavaScript. Operators