3.8 The Logical Operators with non Booleans

In the previous lesson, all logical expressions involved boolean operands. In JavaScript — unlike many other languages — you can also use logical operators with non-boolean values, and that opens very powerful patterns. The result of a logical expression is not necessarily true or false — it is the value of one of the operands.

console.log(false || true);    // true
console.log(false || 'Toto');  // "Toto"
console.log(false || 1);       // 1

Truthy and falsy values

When the engine evaluates a non-boolean operand, it interprets it as either truthy or falsy. The falsy values in JavaScript are:

  • undefined
  • null
  • 0
  • false
  • '' (empty string)
  • NaN (not a number, returned by invalid math)

Any other value is truthy. So 'Toto' (a non-empty string) is truthy, and so is the number 1.

Short-circuit evaluation

With ||, the engine evaluates operands from left to right and returns the first truthy one it finds — then stops. In false || 1 || 2, evaluation returns 1 immediately; 2 is ignored. That behavior is called short-circuit evaluation.

This is extremely useful to provide default values. Suppose the user can choose a color, otherwise we fall back to a default:

const userColor = 'red';
const defaultColor = 'blue';
const currentColor = userColor || defaultColor;
console.log(currentColor); // "red"

If userColor were undefined (the user skipped selection), the expression would return 'blue'. That's the power of logical operators with non-booleans. In the next demonstration, we'll move on to bitwise operators.