Sub topic 9
Filling In Missing Values with ??=
This chapter assumes you already know how ?? works and how it differs from ||. You should also be comfortable with object property access, getters and setters, and strict mode. The nullish coalescing assignment operator, ??=, combines ?? with assignment. It writes a value into a variable or property only when the current value is null or undefined.
The Basic Behavior
target ??= value reads target. If target is nullish, value is evaluated and assigned. If target holds anything else, including 0, "", false or NaN, nothing is assigned. The right-hand side is not evaluated at all in that case.
const config = { retries: 0, label: "", timeout: null };
config.retries ??= 3; // 0 is not nullish, so it is kept
config.label ??= "default"; // "" is not nullish, so it is kept
config.timeout ??= 1000; // null is replaced
config.port ??= 8080; // missing (undefined) is replaced
console.log(config);
// { retries: 0, label: "", timeout: 1000, port: 8080 }Every assignment expression produces a value, and ??= does too. The whole expression evaluates to the final value of the target: the old value if it was kept, or the new value if it was assigned. You will use this result later for caching and grouping.
let level = null;
const result = (level ??= 1);
console.log(result, level); // 1 1
let count = 0;
console.log((count ??= 10)); // 0It Is Not Shorthand for a = a ?? b
a ??= b is often described as shorthand for a = a ?? b. That description is wrong in a way that matters. The specification defines the operator as closer to this:
let a = null;
const b = 5;
// a ??= b behaves like:
a ?? (a = b);
console.log(a); // 5The assignment sits inside the right operand of ??, so it only runs when a is nullish. a = a ?? b always assigns, even when it writes back the same value. Three practical differences follow from this.
Setters Are Not Triggered When a Value Exists
A setter is a function that runs when a property is assigned. With ??=, the setter is never called if the property already has a non-nullish value. The longhand form always calls it.
const store = {
_theme: "dark",
writes: 0,
get theme() {
return this._theme;
},
set theme(v) {
this.writes++;
this._theme = v;
},
};
store.theme ??= "light";
console.log(store.theme, store.writes); // "dark" 0
store.theme = store.theme ?? "light";
console.log(store.theme, store.writes); // "dark" 1This matters for reactive frameworks, proxies, and objects that log or validate writes. A redundant write can trigger a re-render or a change event even though nothing changed.
The Target Expression Is Evaluated Once
With a computed key, ??= evaluates the key expression one time. The longhand form evaluates it twice, once to read and once to write.
let calls = 0;
function nextKey() {
calls++;
return "a";
}
const obj = {};
obj[nextKey()] ??= 1;
console.log(obj, calls); // { a: 1 } 1
calls = 0;
const obj2 = {};
obj2[nextKey()] = obj2[nextKey()] ?? 1;
console.log(obj2, calls); // { a: 1 } 2If the key expression has side effects or returns a different value each time, the two forms behave differently. The same applies to getObject().prop ??= value, where getObject() runs once.
The Right-Hand Side Is Lazy
The right-hand side is evaluated only when it is needed. Expensive or side-effecting defaults are therefore safe to write inline.
function expensiveDefault() {
console.log("computing default");
return 42;
}
const settings = { answer: 7 };
settings.answer ??= expensiveDefault(); // logs nothing
settings.other ??= expensiveDefault(); // logs "computing default"
console.log(settings); // { answer: 7, other: 42 }Comparing ??=, ||= and &&=
ES2021 added three logical assignment operators at the same time. They share the same short-circuit structure and differ only in the condition they test.
| Operator | Assigns when the target is | Equivalent to | Keeps `0`, `""`, `false`? | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|
| `a ??= b` | `null` or `undefined` | `a ?? (a = b)` | Yes | ||||
| `a \ | \ | = b` | Falsy | `a \ | \ | (a = b)` | No, replaces them |
| `a &&= b` | Truthy | `a && (a = b)` | Leaves them as they are |
let a = 0;
a ||= 5;
console.log(a); // 5
let b = 0;
b ??= 5;
console.log(b); // 0
let c = 0;
c &&= 5;
console.log(c); // 0
let d = 2;
d &&= 5;
console.log(d); // 5The trade-off is the same one covered for ?? versus ||. Use ??= when 0, "" and false are legitimate values. Use ||= only when every falsy value really should be treated as missing, such as a display name where an empty string is unusable.
Common Patterns
Defaults for an Options Object
??= reads well for filling in options one by one. Keep in mind that it changes the object it is applied to. If that object came from the caller, you have changed the caller's data as well. Copy it first.
function connect(options = {}) {
const opts = { ...options };
opts.host ??= "localhost";
opts.port ??= 5432;
opts.ssl ??= false;
return opts;
}
const userOptions = { port: 0, ssl: null };
console.log(connect(userOptions));
// { port: 0, ssl: false, host: "localhost" }
console.log(userOptions);
// { port: 0, ssl: null } (unchanged)Destructuring defaults are the main alternative, and they behave differently. A destructuring default such as { port = 5432 } applies only when the value is undefined. An explicit null gets through. ??= treats null and undefined the same.
function withDestructuring({ port = 5432 } = {}) {
return port;
}
function withNullishAssign(options = {}) {
let port = options.port;
port ??= 5432;
return port;
}
console.log(withDestructuring({ port: null })); // null
console.log(withNullishAssign({ port: null })); // 5432Choose destructuring when null should mean "deliberately empty". Choose ??= when null and undefined should both mean "not provided". JSON data and database rows often use null for missing fields, so ??= tends to fit them better.
Lazy Initialization and Caching
The expression's return value, combined with the lazy right-hand side, makes a compact memoization pattern. Memoization means storing a computed result so that later calls reuse it.
const cache = Object.create(null);
function slowSquare(n) {
console.log(`computing ${n}`);
return n * n;
}
function square(n) {
return (cache[n] ??= slowSquare(n));
}
console.log(square(4)); // logs "computing 4", then 16
console.log(square(4)); // 16 (no computation)This pattern has two edge cases.
The cache also uses Object.create(null) instead of {} for a reason. A plain object literal inherits properties such as constructor and toString from Object.prototype. Those inherited values are not nullish, so ??= leaves them in place.
const plain = {};
plain["constructor"] ??= "my value";
console.log(plain["constructor"] === Object); // true (inherited, not replaced)
const bare = Object.create(null);
bare["constructor"] ??= "my value";
console.log(bare["constructor"]); // "my value"Any time the keys come from user input or external data, use a prototype-free object or a Map.
Grouping Items into Arrays
The returned value lets you create a bucket and use it in one expression:
const people = [
{ name: "Ada", team: "core" },
{ name: "Grace", team: "tools" },
{ name: "Linus", team: "core" },
];
const byTeam = Object.create(null);
for (const person of people) {
(byTeam[person.team] ??= []).push(person.name);
}
console.log(byTeam); // { core: ["Ada", "Linus"], tools: ["Grace"] }??= cannot be used with a Map, because map.get(key) ??= [] is a call expression and not a valid assignment target. That line is a SyntaxError. With a Map, write the check out explicitly:
const groups = new Map();
for (const person of people) {
if (!groups.has(person.team)) groups.set(person.team, []);
groups.get(person.team).push(person.name);
}
console.log(groups.get("core")); // ["Ada", "Linus"]Edge Cases and Errors
Because ??= skips the write when a value is present, some writes that would normally fail never get the chance to fail.
"use strict";
const frozen = Object.freeze({ a: 1 });
frozen.a ??= 2; // no error: a is not nullish, so no write is attempted
console.log(frozen.a); // 1
try {
frozen.b ??= 2; // b is undefined, so a write is attempted on a frozen object
} catch (e) {
console.log(e instanceof TypeError); // true
}
const limit = 10;
limit ??= 20; // no error: the assignment to the const never runs
console.log(limit); // 10Code like the last example can hide a bug that only appears once the const holds null. Use let for any binding you intend to fill in with ??=.
The remaining error cases:
| Code | Result | Reason |
|---|---|---|
| `undeclared ??= 1` | `ReferenceError` | Reading an undeclared variable throws before any check |
| `obj?.prop ??= 1` | `SyntaxError` | An optional chain is not a valid assignment target |
| `getObj() ??= 1` | `SyntaxError` | A call result is not a valid assignment target |
| `obj.prop ??= 1` where `obj` is `null` | `TypeError` | Reading `prop` from `null` throws |
To fill in a property on an object that might not exist, check the object first: if (obj) obj.prop ??= 1;.
Support
Logical assignment operators are part of ES2021. They are supported in Chrome and Edge 85+, Firefox 79+, Safari 14+, and Node.js 15+. For older targets, Babel and TypeScript compile a ??= b down to the a ?? (a = b) form with a temporary variable, which keeps the single-evaluation behavior.
Exercise
Given const state = { count: 0, name: null, tags: undefined };, what does state look like after running state.count ??= 5; state.name ||= "anon"; state.tags &&= ["x"]; state.extra ??= state.count;?
Show answer
{ count: 0, name: "anon", tags: undefined, extra: 0 }. count is 0, which is not nullish, so it is kept. name is null, which is falsy, so ||= assigns "anon". tags is undefined, which is falsy, so &&= does nothing. extra is missing, so it receives the current value of state.count, which is 0.
Exercise
A component's state object has a setter that triggers a re-render on every write. Why is state.theme ??= "light" better than state.theme = state.theme ?? "light" here?
Show answer
??= only performs the write when state.theme is null or undefined. If a theme is already set, the setter is never called, so no re-render happens. The longhand form always assigns, so it calls the setter and triggers a re-render even when the value does not change.
Exercise
A memoized function uses return (cache[key] ??= lookup(key)); and lookup returns null for unknown keys. Users report that lookups for unknown keys are slow every time. Explain the cause and give a fix.
Show answer
The cached null is nullish, so ??= treats the entry as missing and calls lookup again on every request. Fix it by using a Map and checking cache.has(key) before computing, or by storing a wrapper object such as { value: null }, which is not nullish.