Assignment Operators

So far we have seen how = can be used to assign values to variables. Sometimes, when updating a variable using its value, we can shorten the code by including a second operator in front of =. For example: a += 3 is identical to a = a +3Such assignment operators include +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<=, >>=, and >>>=.Note that += can be applied to strings (concatenation).

ECMAScript 2021 introduced three logical assignment operators: &&=, ||=, and ??=. Each only assigns when the corresponding logical operation would evaluate the right-hand side at all, so the assignment is short-circuited — and skipped entirely — otherwise.

a &&= b; a && (a = b); assigns only if a is truthy
a ||= b; a || (a = b); assigns only if a is falsy
a ??= b; a ?? (a = b); assigns only if a is null or undefined
||= is handy for defaults, while ??= only steps in for null/undefined, unlike ||= which also overrides falsy-but-valid values like 0 or ''.
let config = {timeout: 0, retries: null};
config.timeout ||= 5000;   // 0 is falsy, so ||= overrides it
config.retries ??= 3;      // null is nullish, so ??= fills it in
console.log(config);

let obj = {};
obj.count &&= obj.count + 1;   // obj.count is undefined (falsy), so the RHS never runs
console.log(obj.count);

{timeout: 5000, retries: 3} undefined