DEV Community

Temitope Ayodele
Temitope Ayodele

Posted on • Edited on

3

Logical Assignment Operators

Logical Assignment Operators was introduced in the ECMAScript 2021 update. It is a new feature that combines the assignment operators with the logical operators (||, &&, ??). It that allows you to assign a value to a variable if true (&&=), false (||=) or null (??=).

Types of Logical Assignment Operators

  • Logical OR assignment operator ||=
  • Logical AND assignment operator &&=
  • Nullish coalescing assignment operator ??=

Logical OR assignment operator ||=

This accessor is used to assign a value to a variable if the variable is not already assigned. If the variable is already assigned, the value is not changed.

//Syntax

a ||= b
Enter fullscreen mode Exit fullscreen mode

This syntax is also similar to:

if (!a) {
  a = b
}
Enter fullscreen mode Exit fullscreen mode

An example is

let a = 0
a ||= 1
console.log(a) // 1
Enter fullscreen mode Exit fullscreen mode

The above example assigns the value 1 to the variable a if the variable is not already assigned. If the variable is already assigned, the value is not changed.

Logical AND assignment operator &&=

This is used to assign a value to a variable only if the value is a truthy

// Syntax

a &&= b
Enter fullscreen mode Exit fullscreen mode

This syntax is also similar to:

if (a) {
  a = b
}
Enter fullscreen mode Exit fullscreen mode

An example is

let a = 0
a &&= 1
console.log(a) // 0
Enter fullscreen mode Exit fullscreen mode

In the above example, a is a falsy value, so it will not be reassigned. It will only reassign if the value is truthy.

let a = 4
a &&= 1
console.log(a) // 1
Enter fullscreen mode Exit fullscreen mode

Nullish coalescing assignment operator ??=

This is similar to the Logical OR assignment operator ||=, however, it only reassigns if the left operand is null or undefined.

// Syntax

a ??= b
Enter fullscreen mode Exit fullscreen mode

This syntax is also similar to:

if (typeof a === "undefined" || a === null) {
  a = b
}
let a = 0
a ??= 1
console.log(a) // 0
let b = null
b ??= 1
console.log(b) // 1
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay