Logical Assignment Operators in JavaScript
🔍 What Are Logical Assignment Operators?
Logical assignment operators combine logical operations (||, &&, ??) with assignment, providing a concise way to update variables based on logical conditions.
Note
Introduced in ES2021, they help write cleaner, shorter code when updating values conditionally.
⚙️ Types of Logical Assignment Operators
- ||= (Logical OR assignment)
- &&= (Logical AND assignment)
- ??= (Nullish coalescing assignment)
🧪 How They Work
Logical OR Assignment (||=)
let a = null;
a ||= "default";
console.log(a); // "default"Assigns "default" to a if a is falsy (like null, undefined, 0, "", etc.).
Logical AND Assignment (&&=)
let b = "value";
b &&= "updated";
console.log(b); // "updated"Assigns "updated" to b only if b is truthy.
Nullish Coalescing Assignment (??=)
let c = null;
c ??= "fallback";
console.log(c); // "fallback"Assigns "fallback" to c only if c is null or undefined.
📌 Use Cases
- Set default values if variables are missing or falsy.
- Update variables only if they already hold meaningful values.
- Handle null or undefined cases precisely.
🚨 Important Notes
- ||= uses falsy check, so it triggers on 0, "", false as well.
- ??= only triggers on null or undefined, ignoring other falsy values.
- These operators mutate the original variable.
🧾 Summary
- ||= assigns if variable is falsy.
- &&= assigns if variable is truthy.
- ??= assigns if variable is nullish (null or undefined).
- They help write concise conditional assignments.
>>“Logical assignment operators reduce boilerplate and improve readability.”