Logical assignment (&&=, ||=, ??=): short-circuit (ES2021)
What you’ll learn
Section titled “What you’ll learn”- What
&&=,||=and??=do, and which values trigger each one. - Why
x ||= yis not the same asx = x || y. - How to choose between
||=and??=when0,''orfalseare valid values. - Edge cases: setters,
const, frozen objects, function names and invalid targets.
Summary
Section titled “Summary”TL;DR: the three logical assignment operators combine a logical operator with assignment, and short-circuit the assignment itself:
| Operator | Assigns when the left side is | Equivalent to |
|---|---|---|
a &&= b |
truthy | a && (a = b) |
a ||= b |
falsy (false, 0, -0, 0n, '', null, undefined, NaN) |
a || (a = b) |
a ??= b |
nullish (null or undefined) |
a ?? (a = b) |
When no assignment is needed, the right-hand side is not evaluated and nothing is written. They were added in ECMAScript 2021 and are supported by every current browser and server runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”Defaults and conditional updates are everywhere. Before ES2021 they meant repeating the target (settings.pageSize = settings.pageSize || 25) or writing an if. The repetition is more than noise: the long form always assigns, which calls setters and fails on read-only targets even when the value does not change.
Running the samples: save each sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23.
The OrdersPortal app fills in its settings:
const settings = { pageSize: 0, currency: '', region: null, debug: true };
settings.pageSize ||= 25; // 0 is falsy, so it is replacedsettings.currency ??= 'USD'; // '' is not null/undefined, so it is keptsettings.region ??= 'eu'; // null is replacedsettings.debug &&= process.env.NODE_ENV !== 'production'; // only changes a truthy value
console.log(settings);Output (run as NODE_ENV=production node settings.mjs):
{ pageSize: 25, currency: '', region: 'eu', debug: false }If 0 is a meaningful page size, use ??= instead; the falsy-versus-nullish distinction is covered on the nullish coalescing page.
How it works
Section titled “How it works”The specification evaluates a ||= b like this: evaluate the reference a once and read its value; if that value is truthy, return it without evaluating b or assigning; otherwise evaluate b, assign it to a, and return it. &&= and ??= differ only in the test. The expression’s value is the final value of a.
// Short-circuiting: the setter only runs when an assignment is needed.const order = { _note: 'gift wrap', get note() { return this._note; }, set note(v) { console.log('setter called with', v); this._note = v; },};
order.note ||= 'none'; // truthy: nothing happens, no setter callorder.note = order.note || 'none'; // the old idiom always assignsorder.note &&= order.note.trim(); // truthy: the setter runs
// The right-hand side is not evaluated either.let calls = 0;const expensiveDefault = () => { calls++; return []; };const cache = { items: ['o-1'] };cache.items ??= expensiveDefault();console.log('calls:', calls);
// A const binding only throws when an assignment actually happens.const pageSize = 50;pageSize ||= 25; // no assignment, no errortry { pageSize &&= 25; // assignment happens -> TypeError} catch (error) { console.log(error.name, '-', error.message);}
// A frozen object: same rule.const frozen = Object.freeze({ retries: 3 });frozen.retries ??= 5; // no assignment, no error even in strict modetry { frozen.retries &&= 5;} catch (error) { console.log(error.name);}
// Anonymous functions get the variable's name (named evaluation).let onSave;onSave ??= () => {};console.log(onSave.name);
// The left-hand side is evaluated only once.let reads = 0;const store = { counts: { 'o-1': 0 } };const key = () => { reads++; return 'o-1'; };store.counts[key()] ||= 1;console.log(store.counts, 'key reads:', reads);Output:
setter called with gift wrapsetter called with gift wrapcalls: 0TypeError - Assignment to constant variable.TypeErroronSave{ 'o-1': 1 } key reads: 1What the output shows:
order.note ||= 'none'did not call the setter; the old idiom did. With proxies or reactive stores, a needless write can trigger re-renders.pageSize ||= 25on aconstis legal because no assignment happens;pageSize &&= 25throws. The same applies to frozen objects (modules are strict, so a write to a frozen property throws).- Like
=, an anonymous function or class assigned to a plain identifier gets that identifier as itsname. - In
store.counts[key()] ||= 1,key()runs once. The long formstore.counts[key()] = store.counts[key()] || 1would call it twice.
Valid targets are the same as for +=: identifiers and property accesses. Destructuring patterns ([a, b] ||= [1, 2]) and optional chains (a?.b ??= 1) are a SyntaxError: Invalid left-hand side in assignment.
Realistic example
Section titled “Realistic example”OrdersPortal builds per-customer summaries for its dashboard. Each operator does one job: ??= fills a missing coupon without touching a real value, &&= trims a note only if there is one, ||= replaces empty notes with a placeholder, and ??= creates each customer’s summary bucket on first use.
// order-summary.mjs - build per-customer summaries for the OrdersPortal dashboard.const orders = [ { id: 'o-1', customer: 'c-7', total: 120, coupon: null, notes: ' rush ' }, { id: 'o-2', customer: 'c-3', total: 0, coupon: 'SPRING' }, { id: 'o-3', customer: 'c-7', total: 45, coupon: 'SPRING', notes: '' },];
function normalize(order, defaults) { const o = { ...order }; o.coupon ??= defaults.coupon; // only null/undefined get the default o.notes &&= o.notes.trim(); // trim only when there is a non-empty note o.notes ||= '(none)'; // '' and undefined both become a placeholder return o;}
function summarize(list, defaults = { coupon: 'NONE' }) { const byCustomer = {}; for (const order of list.map((o) => normalize(o, defaults))) { const summary = (byCustomer[order.customer] ??= { orders: [], revenue: 0, coupons: new Set() }); summary.orders.push(order.id); summary.revenue += order.total; // 0 is a real total: no || here summary.coupons.add(order.coupon); } return byCustomer;}
console.log(normalize(orders[0], { coupon: 'NONE' }));console.log(summarize(orders));
// Lazily created, memoized client: built on first use only.let client;function getClient() { return (client ??= { baseUrl: 'https://api.example.test', createdAt: Date.now() });}console.log(getClient() === getClient());Output:
{ id: 'o-1', customer: 'c-7', total: 120, coupon: 'NONE', notes: 'rush'}{ 'c-7': { orders: [ 'o-1', 'o-3' ], revenue: 165, coupons: Set(2) { 'NONE', 'SPRING' } }, 'c-3': { orders: [ 'o-2' ], revenue: 0, coupons: Set(1) { 'SPRING' } }}true(byCustomer[key] ??= {...}) is the idiom to remember: because the expression returns the final value, it creates the bucket if missing and hands it back in one step. getClient() uses the same idea for lazy initialization.
Common mistakes
Section titled “Common mistakes”- Using
||=when0,''orfalseare valid.quantity ||= 1turns a deliberate0into1. Use??=unless every falsy value really means “missing”. - Assuming
x ||= yequalsx = x || y. The long form always writes. Do not “simplify” code that relies on that write. - Expecting a side effect on the right to run. In
count ??= loadCount(),loadCount()is skipped whencountis already set. Do not put work that must always happen there. - Precedence surprises with
??.a ??= b || cis fine (the right side is a full expression), but mixing??with||or&&inside an expression without parentheses, as ina ?? b || c, is aSyntaxError. - Optional chaining on the left.
config?.retries ??= 3is not allowed. Make sure the object exists first, for example(config ??= {}).retries ??= 3.
When to use it and when not to
Section titled “When to use it and when not to”Use logical assignment for defaults, lazy initialization and conditional updates of a single target. Prefer something else when:
- You need several defaults at once. Object spread or destructuring defaults, such as
{ pageSize: 25, ...userSettings }, are clearer. Note that destructuring defaults apply only toundefined, notnull. - The logic has several branches. Use an
ifstatement. - You are grouping into a
Map. ES2026’sMap.prototype.getOrInsert()andgetOrInsertComputed()(Chrome 145, Firefox 144, Safari 26.2, Node.js 26 according to MDN’s compatibility data) do this directly. To group a whole array at once, useObject.groupBy()(ES2024).
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, all three operators are supported in Chrome 85, Edge 85, Firefox 79, Safari 14 (including iOS), Node.js 15.0.0, Deno 1.2 and Bun 1.0. Internet Explorer never supported them. As syntax they cannot be polyfilled, but transpilers rewrite them: TypeScript with a target below ES2021 emits a.x || (a.x = 1) for a.x ||= 1, which keeps the short-circuit.
Interview questions
Section titled “Interview questions”1. What is the difference between a ||= b and a = a || b?
Both leave a with the same value, but ||= assigns only when a is falsy. a = a || b always assigns, so it calls setters, triggers proxy traps, and throws for const bindings or read-only properties even when the value would not change. It also evaluates the target expression twice.
2. When would you choose ??= over ||=?
When falsy values such as 0, '' or false are legitimate. ??= only replaces null and undefined; ||= replaces every falsy value.
3. What does x &&= f(x) do, and where is it useful?
It replaces x with f(x) only when x is truthy, for example trimming a note only if one exists, or mapping an optional value without an if. If x is falsy, f is not called.
4. Senior scenario: a reactive UI store re-renders on every property write, and profiling shows thousands of needless renders from code like state.filters = state.filters || defaultFilters. What do you change?
Replace the long form with state.filters ||= defaultFilters (or ??= if empty values are valid), so no write happens when the value is already set and the store’s proxy trap never fires. Check each site for code that relied on the unconditional write, confirm the transpiler output keeps the short-circuit (a || (a = b)), enforce the pattern with ESLint’s logical-assignment-operators rule, and add a render-count test to catch regressions.
Key takeaways
Section titled “Key takeaways”&&=,||=and??=(ES2021) assign only when the left side is truthy, falsy or nullish respectively.- They short-circuit the whole assignment: no right-hand evaluation, no setter call, no error on
constor frozen targets when nothing changes. - Prefer
??=for defaults unless every falsy value really means “missing”. (obj[key] ??= init)creates and returns a value in one step.
Related pages
Section titled “Related pages”- Nullish coalescing (??): the operator behind
??=, and the falsy-versus-nullish distinction. - Optional chaining (?.): safe reads, which pair with
??=for safe defaults. - Exponentiation operator: another compound assignment,
**=. - Operators: assignment and logical operators.
- Truthy and falsy values: what
||=and&&=test.
Official references
Section titled “Official references”- ECMAScript Language Specification, Assignment Operators (current draft; logical assignment first published in ECMAScript 2021, 12th edition)
- ECMAScript 2021 Language Specification (ECMA-262, 12th edition)
- TC39 proposal: Logical Assignment Operators
- MDN: Logical AND assignment (&&=)
- MDN: Logical OR assignment (||=)
- MDN: Nullish coalescing assignment (??=)