JavaScript ES6 provides three useful logical assignment operators:
&&=
||=
??=
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.
expression1 &&= expression2
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 ||=
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.
expression ||= expression2
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 ??=
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.
expression ??= expression2
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.