Sub topic 2
How && Picks the First Falsy Operand
This chapter assumes you know the falsy values (false, 0, -0, 0n, "", null, undefined, NaN) and that || returns an operand rather than a boolean.
What && Returns
a && b evaluates a first. If a is falsy, the result is a itself. Otherwise the result is b. In a chain, && returns the first falsy operand, or the last operand if every operand is truthy.
console.log("a" && "b"); // "b"
console.log(0 && "b"); // 0
console.log("a" && "" && 1); // ""
console.log(1 && 2 && 3); // 3A common mistake is to expect true or false here. You get one of the original values back, and its type is unchanged.
Short-Circuit Evaluation: When the Right Side Never Runs
When the left operand already decides the result, JavaScript skips the right operand completely. Any function calls, assignments, or other side effects in it never run.
function log(msg) {
console.log(msg);
return msg;
}
false && log("skipped"); // nothing is logged
true || log("skipped"); // nothing is logged
true && log("runs"); // logs "runs"This is why user && user.name does not throw when user is null. The property read on the right never happens.
Default Values with || and the 0 and Empty-String Trap
value || fallback is a common way to supply a default. It replaces every falsy value, including values you may want to keep.
const settings = { volume: 0, name: "" };
console.log(settings.volume || 50); // 50, the valid 0 is lost
console.log(settings.name || "Anonymous"); // "Anonymous", "" is lost
console.log(settings.theme || "light"); // "light"Exercise
What do console.log(null && f()) and console.log("" || 0 || "x") print, and is f called?
Show answer
The first prints null, and f is never called because the falsy left operand short-circuits &&. The second prints "x", because "" and 0 are both falsy and "x" is the last operand.