ES12 – Logical Assignment Operators

ES12 – Logical Assignment Operators

It’s about time tc39 decided to rollout this feature. I think we all have been in a state of our programming where we wished this feature existed.
Let me dive into codes and examples to explain the new operators to you.


1. ??= Logical nullish assignment operator
Nullish means “null” or “undefined”.

Definition: This operator check assigns RHS to LHS only if the check for the LHS is “null” or “undefined”.

let a = null;
let b = 2;
a ??= b;
console.log('a: ', a) // a: 2

In the above example, value of “a” is “null” and value of “b” is 2. the ??= operator checks if the a is “null” or “undefined”, if it’s true then assigns the value of “b” to “a”.
The above is code is equivalent to the following code where we achieve the same thing without the ??= operator.

let a = null;
let b = 2;
if (a===null || a===undefined) {
a = b;
} 
console.log('a: ', a) // a: 2


Remember that the operator works only when the value of LHS is “null” or “undefined”. So if the value of “a” was to be 5, then the assignment wont happen.

let a = 5;
let b = 2;

a ??= b;

console.log('a: ', a) // a: 5

2. &&= Logical OR assignment operator

Definition: This operator check assigns RHS to LHS only if the check for the LHS is a “truthy” value. In other words “true”.

let a = true;
let b = 2;
a &&= b;
console.log('a: ', a) // a: 2

In the above example, value of “a” is “true” and value of “b” is 2. the &&= operator checks if “a” is “true” , if yes, then it assigns the value of “b” to “a”.
The above is code is equivalent to the following code where we achieve the same thing without the &&= operator.

let a = true;
let b = 2;
if (a) {
a = b;
} 
console.log('a: ', a) // a: 2


If the value of “a” was to be “false”, then the assignment wont happen. example:

let a = false;
let b = 2;
a &&= b;
console.log('a: ', a) // a: false

3. ||= Logical OR assignment operator


Definition: This operator assigns RHS to LHS only if the check for LHS is a “falsy” value. In other words “false”.

let a = false;
let b = 2;
a ||= b;
console.log('a: ', a) // a: 2

In the above example, value of “a” is “false” and value of “b” is 2. the ||= operator checks if “a” is “false” , if yes, then it assigns the value of “b” to “a”.
The above is code is equivalent to the following code where we achieve the same thing without the ||= operator.

let a = false;
let b = 2;
if (!a) {
a = b;
} 
console.log('a: ', a) // a: 2


If the value of “a” was to be “true”, then the assignment wont happen. example:

let a = true;
let b = 2;
a ||= b;
console.log('a: ', a) // a: true