Logical Assignment Operators w JavaScript
JavaScript offers a powerful set of operators that allow you to perform logic operations and assignment in a single step. These operators are known as Logical Assignment Operators.
There are three main logical assignment operators in JavaScript:
- ||= – Logical OR assignment
- &&= – Logical AND assignment
- ??= – nullish coalescing assignment
Let’s take a closer look at each of these operators:
Logical OR assignment (||=)
The Logical OR assignment operator (||=) assigns the value of the right-hand side to the left-hand side only if the left-hand side is falsy (i.e., null, undefined, 0, false, NaN, or an empty string).
let a = 0;
a ||= 5; // a is now 5
Logical AND assignment (&&=)
The Logical AND assignment operator (&&=) assigns the value of the right-hand side to the left-hand side only if the left-hand side is truthy.
let b = 10;
b &&= 20; // b is now 20
Nullish coalescing assignment (??=)
The Nullish coalescing assignment operator (??=) assigns the value of the right-hand side to the left-hand side only if the left-hand side is null or undefined.
let c;
c ??= 30; // c is now 30
These logical assignment operators can help you write more concise and readable code by combining logic operations and assignments into a single step.
Try experimenting with these operators in your JavaScript code to see how they can simplify your logic operations!