Course contentsShow
← JavaScript
Lesson 1961 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Common Use Cases for Logical Assignment

Practical patterns like default parameters, lazy initialization, and conditional updates using logical assignment.

Common Use Cases for Logical Assignment

You'll learn: The most practical patterns where logical assignment operators shine in real-world JavaScript code.

Why These Operators Exist

Logical assignment operators (||=, &&=, ??=) aren't just syntactic sugar—they solve real problems elegantly. Think of them as specialized tools in your toolbox: while you could use a wrench for everything, sometimes you need a precision screwdriver.

Default Parameters and Configuration

The most common use case is providing default values for configuration objects:

function createUser(options) {
  options = options || {};
  options.role ||= 'guest';
  options.permissions ??= ['read'];
  options.active ??= true;
  
  return options;
}

This pattern ensures missing properties get sensible defaults without overwriting intentionally falsy values (like false or 0).

Lazy Initialization

Use ??= to initialize expensive resources only when needed:

let cachedData;

function getData() {
  cachedData ??= fetchExpensiveData(); // Only runs once
  return cachedData;
}

The value is computed and assigned only if it's null or undefined, perfect for caching.

Conditional Updates

Use &&= to update values only when they already exist:

let score = 85;
let multiplier = 2;

score &&= score * multiplier; // Updates to 170
// If score was 0 or falsy, it stays unchanged

This is cleaner than if (score) score = score * multiplier.

Real-World Object Manipulation

function normalizeConfig(config) {
  config.timeout ??= 5000;
  config.retries ||= 3;
  config.debug &&= process.env.NODE_ENV === 'development';
}

Each operator serves a specific purpose: ??= for nullish defaults, ||= for falsy defaults, &&= for conditional mutations.

Key Takeaway: Logical assignment operators eliminate boilerplate for defaults, lazy initialization, and conditional updates—making your intent clearer while writing less code.