Nimatullah Razmjo

Nimatullah Razmjo

ES2021 - Logical Assignment Operator

Logical assignment operator combines the logical operations(&&, || or ??) with assignment.

ES2021 - Logical Assignment Operator

Subscribe to my newsletter and never miss my upcoming articles

Introduction

ECMAScript or ES is a general-purpose programming language, standardized by Ecma International according to the document ECMA-262. It is a JavaScript standard meant to ensure the interoperability of Web pages across different Web browsers. ECMAScript is commonly used for client-side scripting on the World Wide Web, and it is increasingly being used for writing server applications and services using Node.js.

Syntax

exp1 &&= exp2
exp1 ||= exp2
exp1 ??= exp2

logical AND assignment operator &&=

The logical assignment operator &&= is used between two values, if the first value is truthy then the second value will assign.

let a = 10;
let b = 0;

a &&= 2; 
console.log(a);
#expected output: 2

#Here is an equivalent to it
if (a) {
    a = 2
}

b &&= 10; 
console.log(b);
#expected output: 0

#Here is an equivalent to it
if (b) {
    b = 10;
}

Logical OR Assignment Operator ||=

The logical OR assignment operator ||= is used to check if the first value is not truthy(falsy) then it assigns the second value to it.

let a = null;
let b = 10;

a ||= b
#expected output: 10;

#Here is equivalent to it
if (!a) {
    a = b;
}

Logical Nullish Operator ??=

The logical nullish operator ??= is used to check if the first value is null or undefined then the second value will assign as to the first value.

let a = null;
let b = 20;

a ??= b;
console.log(a);
# expected output: 20

#Here is equivalent to it
if ( a == null || a == undefined) {
   a = b;
}

Browser compatibility

Node : 15.0.0, Chrome : 85, Edge :85, Firfox : 79, Safari:14,

Thank you for reading this article. I hope you found it useful.

#ecmascript#javascript#features
 
Share this