What are logical assignment operators in JavaScript?

JavaScript ES6 provides three useful logical assignment operators:

  1. &&=
  2. ||=
  3. ??=

The &&= operator

The &&= is pronounced as “Logical AND assignment operator” and is used in between two values.

If the first value is truthy, then the second value is assigned. It is evaluated left to right.

Syntax

expression1 &&= expression2

Example:

  • JavaScript
Console

Explanation

In the first evaluation on line 5, expression1 is falsy. The expression1 value will not change.

In the second evaluation on line 7, expression2 is truthy. The expression3 value will be assigned to expression2.

The ||= operator

The ||= is pronounced as “Logical OR assignment operator” and is used in between two values.

If the first value is falsy, then the second value is assigned. It is evaluated left to right.

Syntax

expression ||= expression2

Example:

  • JavaScript
Console

Explanation

In the first evaluation on line 5, the expression1 is falsy. The expression2 value will be assigned to expression1.

In the second evaluation on line 7, expression2 is truth. The expression2 value will not change.

The ??= operator

The ??= is pronounced as “Nullish coalescing assignment operator” and is used in between two values.

If the first value is undefined or null, then the second value is assigned. It is evaluated left to right.

Syntax

expression ??= expression2

Example:

  • JavaScript
Console

Explanation

In the first evaluation on line 5, expression1 is null. The expression2 value will be assigned to expression1.

In the second evaluation on line 7, expression2 is neither null nor undefined. The expression2 value will not change.

Free Resources