Logical Assignment Operators in JS

Logical Assignment Operators in JS

Logical assignment operators are a very new feature in JavaScript.
Never heard of them? then this article is for you.

There are three logical assignmet operators in JavaScript

  1. Logical OR assignment operator (||=)
  2. Logical AND assignment operator (&&=)
  3. Nullish assignment (??=)

1. Logical OR assignment:

It performs an assignment if the logical operation would evaluate the right-hand side. In other words, x ||= y is equivalent to:

x || (x = y);

which means that the value of y will be assigned to x if x is falsy.

Examples

let name;  
name ||= 'John'  
console.log(name)  // John  

let person = {name: 'Percy'};  
person.age ||= 30;
console.log(person) // {name: 'Percy', age: 30}

Reference: Logical OR Assignment MDN

2. Logical AND assignment:

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

let a = 1;
let b = 0;

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

b &&= 2;
console.log(b);
// expected output: 0

Reference: Logical AND Operator MDN

3. Logical Nullish assignment:

The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).

function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

Reference: Logical Nullish assignment MDN

That's it for this blog guys, thank you for reading.
I hope you found it helpful, if you did please give a like and share.
This is my first blog on hashnode, if there is any mistake or room for improvement, please let me know.

Follow me on twitter