Conditional Operand Selectors
&& and || are often described as returning true or false, but they actually return one of their two operands. Each one looks at its left operand, decides whether it is truthy or falsy, and selects either that operand or the right one:
a && breturnsaifais falsy, and otherwise returnsb.a || breturnsaifais truthy, and otherwise returnsb.
The value returned is the operand itself, not a boolean version of it:
console.log(0 && 'text');console.log(5 && 'text');console.log('' || 'text');console.log('hi' || 'text');console.log(null || 0 || undefined);console.log(1 && 'a' && 'b');This prints:
0texttexthiundefinedbIn a chain, || returns the first truthy operand, or the last operand if none is truthy. && returns the first falsy operand, or the last operand if none is falsy. The falsy values are false, 0, -0, 0n, '', null, undefined and NaN, as Basic IF Statements shows.
Inside an if, this makes no difference, because the selected value is then tested for truthiness, which gives the same answer as a true boolean result. The behaviour matters when the result is stored or displayed.
Choosing a value
Section titled “Choosing a value”|| picks a fallback when the first value is missing, and && picks a value only when a condition holds:
const user = { name: 'Tom', nickname: '' };
const displayName = user.nickname || user.name;const greeting = user.name && `Hello, ${user.name}`;
console.log(displayName);console.log(greeting);This prints:
TomHello, TomThe pitfall: falsy values that are real
Section titled “The pitfall: falsy values that are real”|| treats every falsy value as missing, including 0 and the empty string, which are often valid:
const settings = { volume: 0 };
const volume = settings.volume || 50;console.log(volume);This prints:
50The volume was deliberately set to 0, but || replaced it. The nullish coalescing operator ?? falls back only for null and undefined, so settings.volume ?? 50 keeps the 0.
&& has the matching problem when its result is displayed. In React, for example, {count && <Badge />} renders the number 0 on the page when count is 0, because && selects the 0 and React renders numbers. React renders nothing for false, null and undefined, so writing {count > 0 && <Badge />} makes the left operand a boolean and avoids it.
Steve Griffith covers this topic in his video Javascript Conditional Operand Selectors.