Mastering JavaScript’s &&= and ??= Operators: Cleaner Conditional Assignments

This article explains the ES2021 logical assignment operators &&= and ??=, detailing their behavior, differences from traditional patterns, providing practical code examples, and showcasing scenarios where they simplify conditional updates and default value handling in JavaScript.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Mastering JavaScript’s &&= and ??= Operators: Cleaner Conditional Assignments

Logical AND Assignment Operator &&=

How &&= works

The &&= operator combines the logical AND ( &&) with assignment ( =). It assigns the right‑hand value to the left‑hand variable only when the left‑hand variable is truthy, allowing a more concise replacement for an if statement followed by an assignment.

// Traditional if statement
if (x) {
  x = y;
}

// Using logical AND
x = x && y;

// Using &&= (ES2021)
x &&= y;

Truthy and falsy values

In JavaScript, the following values are considered falsy:

false
0
''

(empty string)

null
undefined
NaN

All other values are truthy.

Example analysis

Example 1: User login status

let isLoggedIn = true;
isLoggedIn &&= getUserData(); // if already logged in, fetch user data

function getUserData() {
  return { name: 'ConardLi', age: 17 };
}

// Result: isLoggedIn becomes { name: 'ConardLi', age: 17 }

Example 2: Stock update

let stock = 17;

function sell(quantity) {
  stock >= quantity &&= stock - quantity;
}

sell(5);  // stock becomes 12
sell(17); // stock remains 12 because the condition fails for the second call

The sell function reduces the stock only when enough items are available, preventing negative inventory.

Typical use cases

(1) Conditional property update

let config = {
  debugMode: true,
  logLevel: null
};

// Set logLevel only when debugMode is true
config.debugMode &&= (config.logLevel = 'verbose');
// Result: config.logLevel is 'verbose'

(2) Chained conditional assignments

let user = {
  isActive: true,
  hasMembership: true
};

// Apply discount only when both conditions are true
user.isActive &&= user.hasMembership &&= applyDiscount();

function applyDiscount() {
  return 'Discount Applied';
}
// Result: user.hasMembership becomes 'Discount Applied'

Nullish Coalescing Assignment Operator ??=

How ??= works

The ??= operator merges the nullish coalescing operator ( ??) with assignment. It assigns the right‑hand value to the left‑hand variable only when the left‑hand variable is null or undefined, making it ideal for providing default values without overwriting other falsy values.

// Traditional if statement
if (options.timeout === null || options.timeout === undefined) {
  options.timeout = 3000;
}

// Using nullish coalescing
options.timeout = options.timeout ?? 3000;

// Using ??= (ES2021)
options.timeout ??= 3000;

Comparison with other assignment patterns

Using the logical OR ( ||) for defaults treats 0, '', and false as needing replacement, which can lead to unintended overwrites.

let delay = 0;
delay = delay || 1000; // delay becomes 1000 (incorrect)

By contrast, ??= only reacts to null or undefined:

let delay = 0;
delay ??= 1000; // delay remains 0 (correct)

Practical scenarios

??=

is perfect for initializing variables that may be undefined while preserving legitimate falsy values.

let score = 0;
score ??= 100; // stays 0

let tag = '';
tag ??= 'default'; // stays ''

let active = false;
active ??= true; // stays false

It is also useful for setting default configuration options:

function initializeSettings(settings) {
  settings.theme ??= 'light';
  settings.notificationsEnabled ??= true;
  settings.autoSaveInterval ??= 300;
  return settings;
}

Conclusion

&&=

assigns only when the left‑hand side is truthy, making it suitable for conditional updates that should not disturb falsy values. ??= assigns only when the left‑hand side is null or undefined, providing a safe way to set default values without affecting other falsy data.

Incorporating these operators can lead to cleaner, more expressive JavaScript code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptprogramming?=es2021logical-assignment??=
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.