2 min read

Truthy and Falsy Values

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN).

1. Falsy Values

There are only 8 falsy values in JavaScript. If you memorize these, you know that everything else is truthy.

  1. false: The boolean keyword.
  2. 0: The number zero.
  3. -0: The number negative zero.
  4. 0n: BigInt zero.
  5. "" (or '', ``): Empty string.
  6. null: The absence of any value.
  7. undefined: The primitive value.
  8. NaN: Not a Number.
if (0) {
  // This code will NOT run
}

2. Truthy Values

Everything that is not on the list above is truthy. This includes some values that might seem "empty" or "false" in other languages.

  • "0" (a string containing zero)
  • "false" (a string containing the text "false")
  • [] (an empty array)
  • {} (an empty object)
  • function() {} (an empty function)
if ([]) {
  console.log("Empty arrays are truthy!"); // This runs
}

if ("0") {
  console.log("String '0' is truthy!"); // This runs
}

3. Logical Operators and Short-Circuiting

Truthy and falsy values are crucial when using logical operators || (OR) and && (AND).

OR (||)

Returns the first truthy value, or the last value if all are falsy.

const name = "";
const displayName = name || "Guest"; 
console.log(displayName); // "Guest" (because "" is falsy)

AND (&&)

Returns the first falsy value, or the last value if all are truthy.

const isLoggedIn = true;
const user = { name: "Alice" };

// If isLoggedIn is truthy, return user.name
const userName = isLoggedIn && user.name; 
console.log(userName); // "Alice"

4. Double Bang (!!)

You can convert any value to its boolean equivalent using the double NOT operator (!!).

console.log(!!"hello"); // true
console.log(!!0);       // false
console.log(!!{});      // true

programming/javascript/vanilla/javascript programming/javascript/vanilla/type-coercion