Sub topic 4
Short-Circuiting with &&, ||, and ??
This chapter assumes you already know which values are truthy and which are falsy, and that you can read an if statement. It also assumes you are comfortable with functions, objects, and const/let. You will learn what the logical operators return, when they skip evaluating their right side, and how to pick between || and ?? when you supply default values.
What the Operators Actually Return
Many developers think && and || produce true or false. They don't. Each one returns one of its operands, unchanged. The result only acts like a boolean when you use it in a condition, where truthiness applies.
a && breturnsaifais falsy. Otherwise it returnsb.a || breturnsaifais truthy. Otherwise it returnsb.a ?? breturnsaifais anything other thannullorundefined. Otherwise it returnsb.
console.log("cat" && "dog"); // "dog"
console.log(0 && "dog"); // 0
console.log("cat" || "dog"); // "cat"
console.log("" || "dog"); // "dog"
console.log(null ?? "dog"); // "dog"
console.log(0 ?? "dog"); // 0
console.log(false ?? "dog"); // falseThe ! operator works differently. It always returns a real boolean. Applying it twice, as in !!value, is a common way to convert any value to true or false, and it gives the same result as Boolean(value).
console.log(!"hello"); // false
console.log(!!"hello"); // true
console.log(!!0); // falseShort-Circuit Evaluation
Short-circuiting means the right operand is evaluated only when it is needed. Once the left side decides the answer, JavaScript never runs the right side. Any function calls, property reads, or side effects in the skipped part do not happen.
You can watch this happen by putting a logging function on each side:
function check(label, value) {
console.log("evaluated", label);
return value;
}
check("a", false) && check("b", true);
// evaluated a
check("c", true) || check("d", true);
// evaluated c
check("e", null) ?? check("f", "fallback");
// evaluated e
// evaluated fGuarding Property Access
The classic use of && is to read a property only if the object exists:
const user = null;
const name = user && user.name;
console.log(name); // null, and no TypeErrorOptional chaining (user?.name) does this job more clearly in modern code, and it returns undefined instead of the falsy left value. The two are not identical. "" && "".length returns "", while ""?.length returns 0, because ?. only stops on null and undefined. That is the same rule ?? uses, which is why the two operators pair well:
const account = { profile: { nickname: "" } };
const guest = {};
console.log(account.profile?.nickname ?? "anonymous"); // ""
console.log(guest.profile?.nickname ?? "anonymous"); // "anonymous"Using && as a Statement
You will see code like isReady && start();. It works, because start() runs only when isReady is truthy. As a standalone statement, though, an if usually reads better, and linters often flag the pattern as an unused expression. Save && for places where you need its value.
Defaults: || vs ??
This is where most bugs with these operators come from. || replaces any falsy value, and that includes 0, "", false, and NaN. Those are often perfectly valid settings.
const settings = { retries: 0, name: "" };
console.log(settings.retries || 3); // 3
console.log(settings.retries ?? 3); // 0
console.log(settings.name ?? "guest"); // ""
console.log(settings.timeout ?? 1000); // 1000If a user configured zero retries, || quietly overrides that choice with 3. ?? treats only "missing" values (null and undefined) as reasons to fall back.
| Left value | `left \ | \ | "d"` | `left ?? "d"` |
|---|---|---|---|---|
| `undefined` | `"d"` | `"d"` | ||
| `null` | `"d"` | `"d"` | ||
| `0` | `"d"` | `0` | ||
| `""` | `"d"` | `""` | ||
| `false` | `"d"` | `false` | ||
| `NaN` | `"d"` | `NaN` | ||
| `"hi"` | `"hi"` | `"hi"` |
Use this decision rule. Reach for ?? when the left side can legitimately be 0, "", or false. Use || only when every falsy value really should be replaced, for example when an empty string from a form field should count as "not provided".
Precedence and Mixing Operators
&& binds more tightly than ||, the same way multiplication binds more tightly than addition. So a || b && c means a || (b && c).
console.log(true || false && false); // true
console.log((true || false) && false); // false?? has a deliberate restriction. You cannot combine it directly with && or || unless you add parentheses. Code such as a ?? b || c is a SyntaxError when the script is parsed, before any of it runs. The language designers did this so you have to say which grouping you mean.
const a = null;
const b = 0;
const c = 7;
// const bad = a ?? b || c; // SyntaxError if uncommented
console.log((a ?? b) || c); // 7
console.log(a ?? (b || c)); // 7
console.log(a ?? b); // 0Even where parentheses are optional, adding them to mixed &&/|| expressions makes the intent obvious to the next reader.
Logical Assignment: ||=, &&=, and ??=
Each operator has an assignment form that short-circuits too. x ??= y assigns only when x is null or undefined. When no assignment is needed, the right side is never evaluated, and on an object property no write happens at all.
| Operator | Assigns when the target is | Equivalent to | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `x \ | \ | = y` | falsy | `x \ | \ | (x = y)` |
| `x &&= y` | truthy | `x && (x = y)` | ||||
| `x ??= y` | `null` or `undefined` | `x ?? (x = y)` |
const optionsA = { retries: 0 };
optionsA.retries ||= 3;
console.log(optionsA.retries); // 3, the 0 was overwritten
const optionsB = { retries: 0 };
optionsB.retries ??= 3;
console.log(optionsB.retries); // 0, kept
const cache = {};
cache.users ??= [];
cache.users.push("ada");
console.log(cache.users); // ["ada"]
const session = { token: "abc" };
session.token &&= session.token.toUpperCase();
console.log(session.token); // "ABC"The cache.users ??= [] line is a common idiom. It creates a container the first time it is needed and reuses it after that.
Common Errors
- Numeric or empty-string defaults with
||.count || 10turns a real0into10. Use??. - Rendering a stray
0. In templates and UI code,items.length && renderList()returns0when the list is empty, and0may show up on screen. Useitems.length > 0 && renderList(). - Expecting a boolean.
const hasName = user && user.name;can holdnull,"", or a string. WriteBoolean(user && user.name)or!!user?.nameif you need a real boolean. - Relying on side effects in the right operand.
isValid || logError()only logs whenisValidis falsy. That is correct, but it is easy to misread later. Anifmakes the intent clear. - Mixing
??with||without parentheses. This is a syntax error, so add explicit grouping.
Exercise
What does each line print? (1) console.log(0 || null || "x"); (2) console.log(0 ?? null ?? "x"); (3) console.log("a" && 0 && "b"); (4) console.log(null && undefined);
Show answer
(1) "x": 0 and null are both falsy, so || moves on to "x". (2) 0: the first operand is not null or undefined, so ?? returns it right away. (3) 0: "a" is truthy, so && moves on to 0, which is falsy and is returned without evaluating "b". (4) null: the left operand is falsy, so && returns it.
Exercise
A function reads const volume = options.volume || 50;. Users report that setting the volume to 0 does nothing. Explain the bug and fix it so that a missing options object is also handled.
Show answer
0 is falsy, so || replaces it with 50. Use nullish coalescing together with optional chaining: const volume = options?.volume ?? 50;. Now 0 is kept, a missing volume property or a null/undefined options object gives 50, and no TypeError is thrown.
Exercise
Given let calls = 0; const next = () => ++calls; const obj = { v: 1 }; obj.v ??= next(); obj.w ??= next();, what are obj.v, obj.w, and calls afterward?
Show answer
obj.v is 1, because it was not null or undefined, so next() was never called. obj.w is 1, because it was undefined, so next() ran once and returned 1. calls is 1.