Understanding JavaScript’s Logical Assignments

Posted by


Logical assignments are expressions in JavaScript that combine logical operators and assignment operators to perform a specific operation. In this tutorial, we will go through the different types of logical assignments in JavaScript and how they can be used in practice.

Logical Assignments Overview
Logical assignments in JavaScript are a more concise way of writing conditional expressions. They allow you to combine logical operators like &&, ||, !, ?? with assignment operators like =, +=, -= to assign a value based on a certain condition.

There are four main types of logical assignments in JavaScript:

  1. Logical AND Assignment (&&=)
  2. Logical OR Assignment (||=)
  3. Nullish Coalescing Assignment (??=)
  4. Logical Nullish Assignment (??=)

Let’s look at each type in more detail.

  1. Logical AND Assignment (&&=)
    The logical AND assignment &&= operator assigns a value to a variable if the variable is truthy. If the variable is falsy, it leaves the variable unchanged.

Here’s an example of how to use the logical AND assignment operator:

let x = 5;
x &&= 10;
// x is now 10 (since 5 is truthy)
  1. Logical OR Assignment (||=)
    The logical OR assignment ||= operator assigns a value to a variable if the variable is falsy. If the variable is truthy, it leaves the variable unchanged.

Here’s an example of how to use the logical OR assignment operator:

let y;
y ||= 20;
// y is now 20 (since y is undefined and therefore falsy)
  1. Nullish Coalescing Assignment (??=)
    The nullish coalescing assignment ??= operator assigns a value to a variable if the variable is null or undefined. If the variable has a value other than null or undefined, it leaves the variable unchanged.

Here’s an example of how to use the nullish coalescing assignment operator:

let z = null;
z ??= 30;
// z is now 30 (since z is null)
  1. Logical Nullish Assignment (??=)
    The logical nullish assignment ??= operator assigns a value to a variable if the variable is null or undefined. If the variable has a value other than null or undefined, it leaves the variable unchanged.

Here’s an example of how to use the logical nullish assignment operator:

let a;
a ??= 40;
// a is now 40 (since a is undefined)

In conclusion, logical assignments in JavaScript are a powerful tool for writing concise and readable code. By combining logical operators with assignment operators, you can perform conditional assignments in a more efficient way. Practice using these operators in your JavaScript code to improve your coding skills.

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@themajesticbeard1497
2 hours ago

Holy shit, that's useful.

1
0
Would love your thoughts, please comment.x
()
x