Logical Assignment in JavaScript: What It Is and How It Works
||=, &&=, and ??=. These operators assign a value to a variable only if a certain logical condition is met, making code shorter and clearer.How It Works
Logical assignment operators in JavaScript work like a shortcut that combines a logical check and an assignment into one step. Imagine you have a box (a variable) and you want to put something inside it only if the box is empty or meets a certain condition.
For example, the ||= operator assigns a new value only if the current value is falsy (like null, undefined, 0, or ''). It’s like saying, "If the box is empty or false, put this new thing inside." The &&= operator does the opposite: it assigns a new value only if the current value is truthy. The ??= operator assigns a value only if the current value is null or undefined, which is useful when you want to keep zero or empty strings but fill in missing values.
This makes your code cleaner and easier to read because you don’t have to write the full if-statement every time you want to assign conditionally.
Example
This example shows how to use the three logical assignment operators to assign values based on conditions.
let a = null; a ||= 'default'; let b = 'hello'; b &&= 'world'; let c = 0; c ??= 42; console.log(a); console.log(b); console.log(c);
When to Use
Use logical assignment operators when you want to assign a value only if a variable meets a certain condition, like being empty, missing, or truthy. This is common when setting default values, updating state, or handling optional data.
For example, if you want to give a default username when none is provided, ||= is perfect. If you want to update a value only when it already exists, &&= helps. And if you want to fill in missing values but keep zeros or empty strings, ??= is the right choice.
Key Points
||=assigns if the variable is falsy.&&=assigns if the variable is truthy.??=assigns if the variable is null or undefined.- Logical assignment operators make code shorter and easier to read.
- They help handle default values and conditional updates cleanly.
Key Takeaways
||= assigns when a variable is falsy, &&= when truthy, and ??= when null or undefined.