Sub topic 17
Logical Operators: ||, &&, and ??
This chapter assumes you already know the truthy and falsy rules (ToBoolean) and the difference between null and undefined, both covered in earlier chapters. It builds on them to explain what the logical operators actually return, when they stop evaluating, and how to pick between || and ?? for default values.
The working model: operators that return operands
In many languages, || and && always produce true or false. JavaScript works differently. Both operators use ToBoolean only to decide which operand to return, and then they return that operand unchanged.
a || breturnsaifais truthy. Otherwise it returnsb.a && breturnsaifais falsy. Otherwise it returnsb.a ?? breturnsaifais neithernullnorundefined. Otherwise it returnsb.
console.log("a" || "b"); // "a": first truthy operand
console.log(0 || "b"); // "b"
console.log("" && "next"); // "": first falsy operand
console.log("x" && "next"); // "next": all truthy, so the last operand
console.log(0 ?? "b"); // 0: 0 is not nullish
console.log(null ?? "b"); // "b"
console.log(typeof (1 && "yes")); // "string", not "boolean"When you need a real boolean, convert explicitly with Boolean(x) or !!x. The ! operator is the only logical operator that always returns a boolean.
Short-circuit evaluation
All three operators evaluate left to right and stop once the result is known. The right operand is never evaluated if it isn't needed. This matters when the right side has side effects or is expensive.
function log(label, value) {
console.log("evaluated", label);
return value;
}
log("a", 0) || log("b", "fallback"); // logs a, then b; result "fallback"
log("a", 1) || log("b", "fallback"); // logs a only; result 1
log("a", 0) && log("b", "x"); // logs a only; result 0
log("a", null) ?? log("b", "x"); // logs a, then b; result "x"Developers use this behavior for guard expressions such as user && user.save(), which calls save only when user is truthy. Optional chaining, covered below, is usually clearer for this.
|| versus ?? for default values
The classic default idiom value || fallback falls back on every falsy value: 0, -0, 0n, "", NaN, false, null, and undefined. That is fine when none of those is a valid input. It is a bug when 0, "", or false are real values.
function setVolume(options) {
const withOr = options.volume || 50;
const withNullish = options.volume ?? 50;
return [withOr, withNullish];
}
console.log(setVolume({ volume: 0 })); // [50, 0]: || discarded a valid 0
console.log(setVolume({ volume: "" })); // [50, ""]
console.log(setVolume({})); // [50, 50]Use ?? when only "missing" should trigger the fallback. Use || when any empty or falsy value should be replaced, for example turning an empty display name into "Anonymous".
Precedence and the mixing rule
&& binds more tightly than ||, so a || b && c means a || (b && c). The ?? operator has lower precedence than both, and the language forbids combining it directly with || or &&. The ban exists because readers can't easily tell which grouping was intended.
// const bad = null || undefined ?? "x"; // SyntaxError
const ok1 = (null || undefined) ?? "x"; // "x"
const ok2 = null || (undefined ?? "x"); // "x"
console.log(ok1, ok2);This is a parse-time error. The whole script fails to load, not just that line.
Optional chaining: ?.
Optional chaining stops a property access early when the value on its left is null or undefined, and returns undefined instead of throwing a TypeError. It uses the same nullish test as ??, not truthiness, so 0?.toFixed(1) still calls the method.
const user = { profile: { name: "Ada" }, greet() { return "hi"; } };
const nobody = null;
console.log(user?.profile?.name); // "Ada"
console.log(nobody?.profile.name); // undefined: the entire chain stops
console.log(user.missing?.()); // undefined: method call form
console.log(user.greet?.()); // "hi"
const list = null;
console.log(list?.[0]); // undefined: bracket form
const city = nobody?.address?.city ?? "Unknown";
console.log(city); // "Unknown"Two details catch people out.
- Short-circuiting covers the rest of the chain. In
nobody?.profile.name, the.nameaccess is skipped too, so you don't need?.at every step after a nullish value. - Short-circuiting guards only the position where you placed
?.. Inuser?.nickname.length,userexists,user.nicknameisundefined, and reading.lengthfrom it throws. You needuser?.nickname?.length.
You can't assign through optional chaining. user?.name = "x" is a SyntaxError.
Logical assignment: ||=, &&=, ??=
Each logical operator has an assignment form that also short-circuits. a ??= b means a ?? (a = b), not a = a ?? b. When the left side already decides the result, no assignment happens, so setters don't run and read-only properties don't throw.
const config = { retries: 0, label: "", token: "abc" };
config.retries ??= 3; // stays 0: not nullish
config.label ||= "untitled"; // becomes "untitled": "" is falsy
config.token &&= config.token.toUpperCase(); // "ABC": assigned only if truthy
config.timeout ??= 5000; // added: was undefined
console.log(config);
// { retries: 0, label: "untitled", token: "ABC", timeout: 5000 }Common errors
| Mistake | Symptom | Fix | Column | Column |
|---|---|---|---|---|
| `count \ | \ | 10` when 0 is valid | Zero silently becomes 10 | `count ?? 10` |
| Expecting `a && b` to be a boolean | `"0 items"` printed instead of nothing, or JSX renders `0` | `Boolean(a) && b` or `a > 0 && b` | ||
| Mixing `??` with `\ | \ | ` unparenthesized | SyntaxError when the script loads | Add parentheses |
| `obj?.a.b` when `obj.a` may be missing | TypeError on `.b` | `obj?.a?.b` | ||
| Relying on default parameters for `null` | `null` passes through | `x ?? fallback` in the body | ||
| Side effects on the right of `\ | \ | ` | Function sometimes doesn't run | Move the call into its own statement |
Exercise
Predict each result: (a) 0 || null || "x", (b) 0 ?? null ?? "x", (c) "" && 0, (d) NaN || undefined.
Show answer
(a) "x": 0 and null are falsy, so || moves on to "x". (b) 0: 0 is not nullish, so ?? returns it immediately. (c) "": && returns the first falsy operand. (d) undefined: NaN is falsy, so || returns the last operand even though it is also falsy.
Exercise
A function reads const pageSize = settings.pageSize || 20;. Users report that setting pageSize to 0 (meaning "show all") has no effect. Explain why, and give a fix that still defaults to 20 when the setting is absent or null.
Show answer
0 is falsy, so || discards it and returns 20. Use const pageSize = settings.pageSize ?? 20;, which falls back only when the value is null or undefined.
Exercise
Given const order = { customer: null };, what does order.customer?.address.city evaluate to, and what does order.shipping?.address.city evaluate to? Does either throw?
Show answer
Both evaluate to undefined and neither throws. In each case the value before ?. (null in the first, undefined in the second) is nullish, so the rest of the chain, including .address.city, is skipped.
Exercise
What is the difference between obj.count ??= 1 and obj.count = obj.count ?? 1 when obj.count is already 5 and count is defined by a setter that logs each call?
Show answer
obj.count ??= 1 reads the getter, finds 5, and stops without calling the setter. obj.count = obj.count ?? 1 always assigns, so the setter runs and logs, writing 5 back.