Skip to content

Logical assignment (&&=, ||=, ??=): short-circuit (ES2021)

  • What &&=, ||= and ??= do, and which values trigger each one.
  • Why x ||= y is not the same as x = x || y.
  • How to choose between ||= and ??= when 0, '' or false are valid values.
  • Edge cases: setters, const, frozen objects, function names and invalid targets.

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).

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 replaced
settings.currency ??= 'USD'; // '' is not null/undefined, so it is kept
settings.region ??= 'eu'; // null is replaced
settings.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.

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 call
order.note = order.note || 'none'; // the old idiom always assigns
order.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 error
try {
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 mode
try {
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 wrap
setter called with gift wrap
calls: 0
TypeError - Assignment to constant variable.
TypeError
onSave
{ 'o-1': 1 } key reads: 1

What 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 ||= 25 on a const is legal because no assignment happens; pageSize &&= 25 throws. 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 its name.
  • In store.counts[key()] ||= 1, key() runs once. The long form store.counts[key()] = store.counts[key()] || 1 would 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.

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.

  • Using ||= when 0, '' or false are valid. quantity ||= 1 turns a deliberate 0 into 1. Use ??= unless every falsy value really means “missing”.
  • Assuming x ||= y equals x = 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 when count is already set. Do not put work that must always happen there.
  • Precedence surprises with ??. a ??= b || c is fine (the right side is a full expression), but mixing ?? with || or && inside an expression without parentheses, as in a ?? b || c, is a SyntaxError.
  • Optional chaining on the left. config?.retries ??= 3 is not allowed. Make sure the object exists first, for example (config ??= {}).retries ??= 3.

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 to undefined, not null.
  • The logic has several branches. Use an if statement.
  • You are grouping into a Map. ES2026’s Map.prototype.getOrInsert() and getOrInsertComputed() (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, use Object.groupBy() (ES2024).

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.

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.

  • &&=, ||= 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 const or 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.