Logical assignment operators (&&=, ||=, ??=)
ECMAScript 2021 (ES12) introduced three logical assignment operators: &&=
, ||=
, and ??=
. These operators combine logical operations with assignment, simplifying code writing in specific scenarios. They use short-circuiting to achieve conditional assignment, making it more efficient to handle common issues like default values and nullish coalescing.
Logical AND Assignment Operator (&&=)
The &&=
operator performs assignment only when the left-hand operand is truthy. Its behavior is equivalent to x = x && y
, but the right-hand expression is evaluated only if x
is truthy.
let a = 1;
let b = 0;
a &&= 2; // a = 1 && 2 → a = 2
b &&= 2; // b = 0 && 2 → b = 0
console.log(a); // 2
console.log(b); // 0
Typical use cases include object property initialization:
const config = {};
// Traditional approach
if (!config.timeout) {
config.timeout = 3000;
}
// Using &&=
config.timeout &&= 3000;
Logical OR Assignment Operator (||=)
The ||=
operator performs assignment when the left-hand operand is falsy, equivalent to x = x || y
. It is useful for setting default values:
let user = {
name: '',
level: 0
};
user.name ||= 'Anonymous'; // name = '' || 'Anonymous' → 'Anonymous'
user.level ||= 1; // level = 0 || 1 → 1
console.log(user); // { name: 'Anonymous', level: 1 }
Practical example: Caching data loading
let cache = null;
function loadData() {
cache ||= fetch('/api/data').then(res => res.json());
return cache;
}
Nullish Coalescing Assignment Operator (??=)
The ??=
operator specifically targets null
or undefined
, performing assignment only when the left-hand operand is nullish. Unlike ||=
, it does not trigger assignment for falsy values like 0
or ''
:
let settings = {
width: 0,
title: null
};
settings.width ??= 100; // width = 0 ?? 100 → 0
settings.title ??= 'Untitled'; // title = null ?? 'Untitled' → 'Untitled'
console.log(settings); // { width: 0, title: 'Untitled' }
Form handling example:
function processInput(input) {
input.value ??= '';
input.valid ??= false;
return input;
}
Operator Precedence and Considerations
These new operators have lower precedence than the regular assignment operator (=
) but higher than the comma operator:
let x = 1;
let y = 2;
x ||= y += 3; // Parsed as x ||= (y += 3)
console.log(x, y); // 1, 5
Important edge cases:
// Combining with optional chaining
const obj = { nested: {} };
obj.nested?.prop ??= 'default'; // Safe assignment
// Cannot be used with undeclared variables
undefinedVar ||= 'value'; // ReferenceError
Performance Comparison and Transpilation
Performance differences compared to traditional approaches:
// Test case
let value = false;
console.time('traditional');
if (!value) { value = getDefault(); }
console.timeEnd('traditional');
console.time('logical');
value ||= getDefault();
console.timeEnd('logical');
Babel transpilation result:
// Original code
x &&= y;
// Transpiled result
x && (x = y);
Browser Compatibility and Usage Recommendations
All modern browsers (Chrome 85+, Firefox 79+, Safari 14+) support these operators. Node.js has supported them since version 15.0.0. For older environments, compatibility can be achieved using the Babel plugin @babel/plugin-proposal-logical-assignment-operators
.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Promise.any()
下一篇:数字分隔符(_)