0
0
JavascriptConceptBeginner · 3 min read

Logical Assignment in JavaScript: What It Is and How It Works

Logical assignment in JavaScript combines logical operations with assignment using operators like ||=, &&=, 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.

javascript
let a = null;
a ||= 'default';

let b = 'hello';
b &&= 'world';

let c = 0;
c ??= 42;

console.log(a);
console.log(b);
console.log(c);
Output
default world 0
🎯

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

Logical assignment operators combine condition checks and assignment in one step.
||= assigns when a variable is falsy, &&= when truthy, and ??= when null or undefined.
They simplify code for setting defaults and conditional updates.
Use them to write cleaner, more readable JavaScript.
They help avoid verbose if-statements for common assignment patterns.