Logical AND assignment (&&=)

The logical AND assignment (x &&= y) operator only assigns if x is truthy.

Try it

Syntax

js

x &&= y

Description

Logical AND assignment short-circuits, meaning that x &&= y is equivalent to:

js

x && (x = y);

No assignment is performed if the left-hand side is not truthy, due to short-circuiting of the logical AND operator. For example, the following does not throw an error, despite x being const:

js

const x = 0;
x &&= 2;

Neither would the following trigger the setter:

js

const x = {
  get value() {
    return 0;
  },
  set value(v) {
    console.log("Setter called");
  },
};

x.value &&= 2;

In fact, if x is not truthy, y is not evaluated at all.

js

const x = 0;
x &&= console.log("y evaluated");
// Logs nothing

Examples

Using logical AND assignment

js

let x = 0;
let y = 1;

x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0

Specifications

Specification
ECMAScript Language Specification
# sec-assignment-operators

Browser compatibility

BCD tables only load in the browser

See also