Sub topic 11
Logical Assignment: ||=, &&= and ??=
This chapter assumes you already know how ||, && and ?? pick an operand, and that the right side of each is skipped once the left side decides the result. It also assumes you can read object property access, getters and setters, and console.log output. Logical assignment adds no new truthiness rules. It packages the short-circuit behavior you already know into an assignment.
ES2021 added three operators:
| Operator | Assigns when the current value is | Common use | Column | Column |
|---|---|---|---|---|
| `a \ | \ | = b` | falsy | Replace any falsy value with a fallback |
| `a &&= b` | truthy | Transform a value only if it is present | ||
| `a ??= b` | `null` or `undefined` | Fill in a missing value, keeping `0`, `""` and `false` |
The Basic Behavior
Here is each operator applied to an options object:
const opts = { retries: 0, label: "" };
opts.retries ||= 3; // retries becomes 3
opts.label ??= "default"; // label stays ""
opts.timeout ??= 1000; // timeout becomes 1000
let token = "abc";
token &&= token.toUpperCase(); // "ABC"
console.log(opts, token);
// { retries: 3, label: "", timeout: 1000 } ABCLook at each line:
opts.retriesis0, which is falsy, so||=assigns3. If0was a valid retry count, this line has a bug. It is the same trap that||has with defaults.opts.labelis"", which is not nullish, so??=leaves it alone.opts.timeoutdoes not exist, so reading it givesundefined, and??=creates the property.tokenis truthy, so&&=replaces it with the uppercase version. Iftokenwerenull,&&=would leave itnulland never calltoUpperCase().
What the Operators Expand To
The most common mental model is a ||= b means a = a || b. That model gives the right final value in ordinary code, but the specification defines something different:
| Shorthand | Actual meaning | Not quite | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|
| `a \ | \ | = b` | `a \ | \ | (a = b)` | `a = a \ | \ | b` |
| `a &&= b` | `a && (a = b)` | `a = a && b` | ||||||
| `a ??= b` | `a ?? (a = b)` | `a = a ?? b` |
The difference is that the assignment itself sits inside the short-circuited part. When the left side decides the result, nothing is written at all. The simpler expansion always writes, even when it writes back the same value.
This is more than a technicality. The next sections show code that behaves differently depending on which expansion is true.
Observable Differences: Setters, Frozen Objects and const
Setters run only when a write happens
A setter is a function that runs on every assignment to a property. With logical assignment you can see whether a write happened:
const config = {
_mode: "dark",
get mode() {
console.log("get");
return this._mode;
},
set mode(value) {
console.log("set", value);
this._mode = value;
}
};
config.mode ||= "light";
// logs: get
config.mode = config.mode || "light";
// logs: get
// logs: set darkThe long form calls the setter even though the value does not change. This matters when a setter has side effects, such as triggering a re-render in a reactive framework, writing to storage, or logging a change event. ||= avoids all of that when no change is needed.
No write means no write error
Frozen objects and const bindings reject assignments. Because logical assignment skips the write, it does not fail when it has nothing to write:
"use strict";
const frozen = Object.freeze({ name: "Ada", nickname: null });
frozen.name ||= "Unknown"; // fine: name is truthy, no write attempted
console.log(frozen.name); // "Ada"
try {
frozen.nickname ??= "A"; // nickname is null, so a write is attempted
} catch (err) {
console.log(err.name); // "TypeError"
}
const limit = 10;
limit ||= 5; // fine: limit is truthy, no assignment
console.log(limit); // 10
try {
limit &&= 20; // limit is truthy, so assignment is attempted
} catch (err) {
console.log(err.name); // "TypeError"
}The left side is read first
Every logical assignment reads its target before deciding anything. If the target is an undeclared variable, the read throws a ReferenceError:
try {
undeclaredThing ??= 1;
} catch (err) {
console.log(err.name); // "ReferenceError"
}A plain assignment undeclaredThing = 1 in sloppy mode would quietly create a global. Logical assignment never does.
The target is evaluated once
For a target like obj[key()], the expression obj[key()] ||= v calls key() once. The long form obj[key()] = obj[key()] || v calls it twice, and the two calls might even return different keys.
let calls = 0;
const store = {};
const key = () => { calls++; return "count"; };
store[key()] ??= 0;
console.log(calls); // 1
store[key()] = store[key()] ?? 0;
console.log(calls); // 3The Expression Has a Value
Like =, each logical assignment is an expression. Its result is the final value of the target: the existing value if nothing was written, or the new value if something was. That makes a grouping idiom very short:
const items = [
{ type: "fruit", name: "apple" },
{ type: "veg", name: "leek" },
{ type: "fruit", name: "pear" }
];
const groups = {};
for (const item of items) {
(groups[item.type] ??= []).push(item.name);
}
console.log(groups); // { fruit: ["apple", "pear"], veg: ["leek"] }The first time a type appears, ??= creates the array and returns it. After that, it returns the existing array. The same pattern works for lazy initialization, where an expensive value is built on first use:
function buildIndex() {
console.log("building index");
return new Map([["a", 1]]);
}
const cache = {};
function getIndex() {
return (cache.index ??= buildIndex());
}
getIndex(); // logs "building index"
getIndex(); // logs nothing; the cached Map is returnedbuildIndex() is on the right side, so it runs only when cache.index is nullish.
Choosing the Right Operator
Choosing between the three follows the same rules as choosing between ||, && and ??:
- Use
??=to fill a missing value. It is the right default for configuration, counters, caches and anything where0,""orfalseare meaningful. - Use
||=only when every falsy value really means "no value", for example a display name where an empty string should be replaced. - Use
&&=to update a value only when it exists, such asuser.email &&= user.email.trim(). If the value is missing, it stays missing and the method is never called onnull.
function normalize(user) {
user.email &&= user.email.trim().toLowerCase();
user.displayName ||= "Guest";
user.loginCount ??= 0;
return user;
}
console.log(normalize({ email: " [email protected] ", displayName: "", loginCount: 0 }));
// { email: "[email protected]", displayName: "Guest", loginCount: 0 }
console.log(normalize({ email: null }));
// { email: null, displayName: "Guest", loginCount: 0 }Common Errors
| Mistake | What happens | Fix | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `count \ | \ | = 10` where `0` is valid | A real `0` is replaced with `10` | Use `count ??= 10` | ||
| `const x = ...; x ??= y` | Throws `TypeError` only when `x` is nullish | Declare with `let` | ||||
| `obj?.prop ??= 1` | `SyntaxError`: an optional chain cannot be an assignment target | Check `obj` first, then `obj.prop ??= 1` | ||||
| `a | = b ?? c` and similar mixes | Hard to read. `??` mixed directly with `\ | \ | ` in other positions is a `SyntaxError` | Add parentheses around the inner expression | |
| Expecting `&&=` to create a property | `&&=` never writes to a missing (`undefined`) property | Use `??=` to create, `&&=` to update |
Exercise
Given const s = { a: 0, b: "x", c: null };, what does s contain after running s.a ||= 5; s.b &&= s.b + "y"; s.c ??= false; s.d &&= 1;?
Show answer
{ a: 5, b: "xy", c: false }. a is falsy, so ||= writes 5. b is truthy, so &&= writes "xy". c is null, so ??= writes false. d is undefined (falsy), so &&= does nothing and no d property is created.
Exercise
An object has a status setter that sends a network request on every assignment. Its current value is "ready". How many requests do obj.status ||= "idle" and obj.status = obj.status || "idle" each send, and why?
Show answer
||= sends zero requests because "ready" is truthy, so the assignment is skipped. The long form sends one request because it always assigns, even though it writes "ready" back unchanged.
Exercise
Why does const max = 3; max ||= 10; run without error, while const max = 0; max ||= 10; throws? What type of error is thrown?
Show answer
||= assigns only when the current value is falsy. 3 is truthy, so no assignment is attempted on the const binding. 0 is falsy, so the assignment is attempted, and assigning to a const throws a TypeError.
Exercise
Rewrite this loop body with a single logical assignment expression: if (index[word] === undefined || index[word] === null) { index[word] = []; } index[word].push(line);
Show answer
(index[word] ??= []).push(line); The ??= creates the array only when the entry is nullish and returns the array in both cases, so push always gets a valid array.