JavaScript Assignment Operators: =, Compound Assignment and Logical Assignment (&&=, ||=, ??=)
Assignment as an expression with a value, chained assignment and its shared-object trap, every compound operator from += to >>>=, why a op= b differs from a = a op b, logical assignment with ||=, &&= and ??= and why it skips the write entirely, plus common patterns and errors.
kvi5hnuCode Sprout team member7 min readOn this page
= looks like the simplest operator in the language, but it has more to it than "store a value". Assignment is an expression with its own value, it groups right to left, it has a dozen compound forms like +=, and since ES2021 it has three logical forms (||=, &&=, ??=) that are the neatest way to set defaults. This article covers all of them.
Plain assignment: =
target = value evaluates the target (which must be an assignable lvalue: a variable, property or array element), then the value, and stores the value. Read = as "becomes" or "gets", never as "equals", which is ===.
The whole assignment is an expression, and its value is the value assigned:
let x;
console.log((x = 5) * 2, x); // the assignment evaluates to 5
let match;
if ((match = /(\d+)/.exec("order 42"))) { // assign and test in one go
console.log(match[1]);
}
10 5
42
The second example, assigning inside a condition, is a known idiom, but it's easy to misread as a comparison. The extra parentheses tell readers (and ESLint's no-cond-assign rule) that it's deliberate. In most code, assigning on a separate line is clearer.
Chained assignment
Assignment is right-associative (article 30), so a = b = c = 0 assigns from right to left, and every variable gets 0. That's fine for primitives. For objects, every variable gets the same object:
let a, b;
a = b = [];
b.push("oops");
console.log(a); // a and b are the same array
let left = [], right = []; // separate arrays: separate initializers
right.push("ok");
console.log(left);
[ 'oops' ]
[]
Also note that let a = b = 0; doesn't declare b: only a is declared, and b = 0 assigns to an existing b. If there's none, strict code throws a ReferenceError, and sloppy code silently creates a global variable (article 20). Declare each variable: let a = 0, b = 0;.
What can't be assigned
for (const code of ["1 = 2", "const k = 1; k = 2;", "let p; p + 1 = 3"]) {
try {
eval(code);
} catch (err) {
console.log(code.padEnd(20), err.name);
}
}
1 = 2 SyntaxError
const k = 1; k = 2; TypeError
let p; p + 1 = 3 SyntaxError
A target that isn't assignable at all is a SyntaxError, found before the code runs. Assigning to a const is a TypeError at run time.
Compound assignment: += and friends
Most binary operators have an assignment form: a op= b means "compute a op b and store it in a".
| Operator | Same as | Typical use |
|---|---|---|
a += b | a = a + b | add to a total, append to a string |
a -= b | a = a - b | subtract |
a *= b | a = a * b | scale |
a /= b | a = a / b | divide |
a %= b | a = a % b | wrap a counter |
a **= b | a = a ** b | square a value (x **= 2) |
a <<= b, a >>= b, a >>>= b | a = a << b and so on | shift bits |
a &= b, a |= b, a ^= b | a = a & b and so on | clear, set and toggle flags (article 32) |
let label = "Total";
label += ": " + 5; // strings: concatenation
console.log(label);
let n = 10;
n -= 3; n *= 2; n /= 7; n **= 3; n %= 5;
console.log(n);
let big = 5n;
big *= 2n; // works with BigInt too
console.log(big);
let s = "x";
s += 1 + 2; // the right side is evaluated first: "x" + 3
console.log(s);
Total: 5
3
10n
x3
The last example is worth noticing: s += 1 + 2 is s = s + (1 + 2), so the right side is a complete expression computed before the +=.
a op= b is not exactly a = a op b
The difference: in a op= b, the target a is evaluated once. In a = a op b, it's evaluated twice. That matters only when the target has side effects:
const scores = [1, 2, 3, 4];
let i = 0;
scores[i++] *= 10; // scores[0] = scores[0] * 10; i is now 1
console.log(scores, i);
const other = [1, 2, 3, 4];
let j = 0;
other[j++] = other[j++] * 10; // other[0] = other[1] * 10; j is now 2
console.log(other, j);
[ 10, 2, 3, 4 ] 1
[ 20, 2, 3, 4 ] 2
The same applies to targets like getRecord().count += 1: the function runs once with +=, twice with the long form.
Logical assignment: ||=, &&= and ??=
ES2021 added assignment forms of the three logical operators (article 34). They short-circuit the whole assignment:
| Operator | Assigns b when a is | Roughly the same as |
|---|---|---|
a ||= b | falsy | a || (a = b) |
a &&= b | truthy | a && (a = b) |
a ??= b | null or undefined | a ?? (a = b) |

const options = { retries: 0, name: "", cache: null };
options.retries ||= 3; // 0 is falsy: replaced
options.name ??= "anonymous"; // "" is not nullish: kept
options.cache ??= new Map(); // null: replaced
console.log(options.retries, JSON.stringify(options.name), options.cache instanceof Map);
let token = "abc", missing = null;
token &&= token.toUpperCase(); // transform only if present
missing &&= missing.toUpperCase();
console.log(token, missing);
3 "" true
ABC null
The same rule as for || versus ?? applies: ??= is usually the right choice for defaults, because it keeps 0, "" and false.
No write at all when the value is kept
The equivalences in the table use a || (a = b), not a = a || b, and the difference is real. With logical assignment, when the value is kept, no assignment happens. With the long form, the variable or property is always written, even if with its own value:
let writes = 0;
const record = {
get status() { return "active"; },
set status(value) { writes++; },
};
record.status ||= "new"; // "active" is truthy: setter not called
record.status ??= "new"; // not nullish: setter not called
console.log(writes);
record.status = record.status || "new"; // always assigns: setter called
console.log(writes);
(function () {
"use strict";
const config = Object.freeze({ level: 1 });
config.level ||= 5; // no write, so no error
try {
config.level = config.level || 5; // writing to a frozen object throws in strict mode
} catch (err) {
console.log(err.name);
}
})();
0
1
TypeError
Skipping the write avoids running setters (which might trigger UI updates, validation or network calls), avoids errors on read-only properties, and is slightly faster.
Everyday patterns
// Initialize a counter before incrementing it
const counts = {};
for (const word of ["red", "blue", "red"]) {
counts[word] ??= 0;
counts[word]++;
}
console.log(counts);
// Lazily create a list the first time it's needed
const groups = {};
(groups.admins ??= []).push("ana");
(groups.admins ??= []).push("cai"); // already exists: reused
console.log(groups);
{ red: 2, blue: 1 }
{ admins: [ 'ana', 'cai' ] }
The second pattern uses the value of the assignment expression: groups.admins ??= [] evaluates to the array, whether it was just created or already there. For maps, ES2026's map.getOrInsert(key, []) does the same job in one method call (part 11).
Destructuring assignment
Assignment also accepts a destructuring pattern on the left, which assigns several targets at once: [a, b] = [b, a] swaps two variables, and ({ width, height } = size) copies two properties. Article 28 covers it in full.
Common questions
Is x += 1 faster than x = x + 1?
No measurable difference for simple variables: engines compile both the same way. Choose by readability. The difference that matters is the single evaluation of complex targets, shown above.
Why does if (x = 5) run even when x was 0?
= assigns 5 and the expression's value is 5, which is truthy. The comparison you meant is x === 5. ESLint's no-cond-assign rule (in the recommended set) catches this typo.
Does a ??= b evaluate b when a already has a value?
No. Like ??, it short-circuits: b is evaluated only if it will be assigned. So cache ??= expensiveSetup() runs the setup at most once.
Can I use logical assignment with optional chaining, like user?.name ??= "x"?
No. Optional chaining can't appear on the left side of any assignment (article 29). Check the object first: if (user) user.name ??= "x";.
Summary
=evaluates the target, then the value, and is itself an expression whose value is the assigned value.- Chained assignment groups right to left; with objects, every variable shares the same object.
- Non-assignable targets are SyntaxErrors; assigning to a
constis a TypeError. a op= bexists for every arithmetic and bitwise operator and evaluates the target only once.a ||= b,a &&= banda ??= bassign only when needed, and when they don't assign, no write happens at all, so setters don't run and frozen properties don't throw.obj.prop ??= defaultis the idiomatic way to set a default without discarding0,""orfalse.
Practice Questions
What are a, b and c after this code?
let a = 1, b = 2, c = 3;
a += b *= c -= 1;
Answer
c is 2, b is 4, and a is 5. Assignment groups right to left: c -= 1 makes c 2, b *= 2 makes b 4, a += 4 makes a 5.
Rewrite this code with logical assignment. Is ||= or ??= closer to the original?
if (!settings.locale) {
settings.locale = "en-US";
}
Answer
settings.locale ||= "en-US"; behaves exactly like the original, which replaces any falsy value. ??= would keep an empty string. Which one is right depends on whether "" is a meaningful locale (it isn't, so ||= is fine here).
What is logged by this code?
let n = 0;
n ||= 10;
n &&= n + 1;
n ??= 99;
console.log(n);
Answer
11. n ||= 10 replaces the falsy 0 with 10, n &&= n + 1 makes it 11 because 10 is truthy, and n ??= 99 does nothing because 11 isn't nullish.
Why is this code usually a bad idea even though it works?
const total = subtotal += tax;
Answer
It changes subtotal as a hidden side effect inside another statement. Someone reading const total = ... won't expect subtotal to change. Write const total = subtotal + tax;, or update subtotal on its own line if that's the intent.
How do you append to an array stored under index[letter], creating the array if it doesn't exist, in one line?
Answer
(index[letter] ??= []).push(word);. The ??= expression evaluates to the existing or newly created array, and push adds to it.
Previous: JavaScript Logical Operators: &&, ||, !, ?? and Short-Circuit Evaluation
Next: JavaScript eval(): Direct vs Indirect eval, Strict Mode and Safer Alternatives

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.