Masterbook/Chapter 10• 1 min read
View Raw Code on GitHub

Explain truthy and falsy values

Explain truthy and falsy values

In JavaScript, every value becomes either true or false when used in a boolean context. Truthy means a value is treated as true; falsy means it is treated as false. This conversion happens with if, while, for conditions, the ternary operator, logical operators like &&, ||, and !, and in APIs that expect a
boolean.

There are exactly seven falsy values: false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN. All other values are truthy, including objects, arrays, functions, non-zero numbers, non-empty strings, and symbols. Even unusual values like "0" (a string containing zero), "false" (a non-empty string), [] (empty array), and {} (empty object) are truthy.

JavaScript does not permanently convert the value; it only interprets it as true or false for that operation using an internal ToBoolean step. This is part of type coercion.

if ("hello") console.log("truthy"); // non-empty string is truthy
if (0) console.log("never runs"); // 0 is falsy
if ([]) console.log("runs"); // empty array is truthy
if ({}) console.log("runs"); // empty object is truthy
if (null) console.log("no"); // null is falsy
console.log(Boolean("")); // false
console.log(Boolean(" ")); // true (string with a space)
console.log(Boolean(123)); // true
console.log(Boolean(0)); // false
console.log(Boolean([])); // true
console.log(Boolean({})); // true

Common misconceptions

  1. Empty arrays and empty objects are falsy. All objects are truthy, even empty ones.
  2. The string "false" is falsy. Any non-empty string is truthy.
  3. NaN behaves like 0 in truthiness. NaN is falsy.

Practice questions

  1. List all falsy values in JavaScript and explain why "0" is truthy but 0 is falsy.
  2. Explain why [] && {} returns {} but [] || {} returns [].
  3. Predict the behavior of if ("0") and if (0) and explain the difference.