Master the New &&= and ??= Operators in JavaScript
The article explains ECMAScript 2021's logical assignment operators &&= and ??=, detailing their semantics, showing traditional equivalents, listing truthy/falsy values, and providing practical code examples and use‑cases for concise 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.
Traditional equivalents:
// using an if statement
if (x) {
x = y;
}
// using logical AND
x = x && y;
// using the new operator (ES2021)
x &&= y;Truthy and Falsy Values
In JavaScript the following are falsy: false, 0, '' (empty string), null, undefined, NaN. All other values are truthy.
Example Walk‑throughs
Example 1 – User login status
let isLoggedIn = true;
isLoggedIn &&= getUserData(); // if already logged in, fetch 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 5
sell(17); // stock stays 5 because 5 >= 17 is falseThe sell function reduces stock only when enough inventory exists, preventing negative stock.
Typical Application Scenarios
(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 checks
let user = { isActive: true, hasMembership: true };
// apply discount only when both conditions are true
user.isActive &&= user.hasMembership &&= applyDiscount();
function applyDiscount() {
return '已应用折扣';
}
// Result: user.hasMembership becomes '已应用折扣'Nullish Coalescing Assignment Operator ??=
How ??= Works
The ??= operator merges the nullish coalescing operator ( ??) with assignment. It assigns the right‑hand value only when the left‑hand variable is null or undefined, leaving other falsy values untouched.
Traditional equivalents:
// using an if statement
if (options.timeout === null || options.timeout === undefined) {
options.timeout = 3000;
}
// using nullish coalescing
options.timeout = options.timeout ?? 3000;
// using the new operator (ES2021)
options.timeout ??= 3000;Comparison with Logical OR
Using || treats 0, '', and false as needing a default, which can produce unintended overwrites:
let delay = 0;
delay = delay || 1000; // delay becomes 1000 (incorrect)With ??= the assignment happens only for null or undefined:
let delay = 0;
delay ??= 1000; // delay remains 0A ternary expression can achieve the same but is more verbose and harder to read.
Advantages
The operator is concise, avoids affecting legitimate falsy values, and clearly signals intent to provide a default only for uninitialized variables.
Application Scenarios
Setting defaults without overriding valid falsy values:
let score = 0;
score ??= 100; // stays 0
let tag = '';
tag ??= 'default'; // stays ''
let active = false;
active ??= true; // stays falseConfiguring default parameters in functions:
function initializeSettings(settings) {
settings.theme ??= 'light';
settings.notificationsEnabled ??= true;
settings.autoSaveInterval ??= 300;
return settings;
}Conclusion
&&=assigns only when the left‑hand side is truthy, ideal for conditional updates that must preserve falsy values. ??= assigns only when the left‑hand side is null or undefined, perfect for providing defaults without disturbing legitimate falsy data.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Cultivation Path
Focused on sharing practical tech content about TypeScript, Vue 3, front-end architecture, and source code analysis.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
