What is truthy and falsy?

Every value in JavaScript becomes true or false when used in a boolean context; the falsy values are false, 0, -0, 0n, "", null, undefined and NaN, and everything else is truthy.

Boolean contexts

if, while, the ternary ? :, &&, ||, !, and Boolean(value) all convert their operand to a boolean.

Surprising truthy values

  • "0" and "false": non-empty strings are truthy.
  • [] and {}: all objects are truthy, even empty ones.
  • new Boolean(false): an object, so truthy.
  • -1, Infinity: any non-zero number is truthy.

Why it matters

Truthiness makes short checks convenient (if (user)), but can hide bugs when 0 or "" are valid values:

  • if (count) is false when count is 0.
  • value || "default" replaces a legitimate 0 or "".

Safer patterns

  • Use ?? when only null/undefined should get a default.
  • Check emptiness explicitly: array.length === 0, Object.keys(obj).length === 0, str.trim() === "".
  • Use value != null to mean "has a value", including 0 and "".

Converting explicitly

Boolean(x) or !!x produce a real boolean, useful when an API expects true/false (for example a React prop like disabled).

Code example

js
1const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
2console.log(falsy.map(Boolean)); // all false
3
4const surprisinglyTruthy = ["0", "false", " ", [], {}, -1, Infinity];
5console.log(surprisinglyTruthy.map(Boolean)); // all true
6
7// The bug: 0 is a valid quantity
8const quantity = 0;
9if (quantity) console.log("has items");
10else console.log("treated as empty!"); // runs - probably not intended
11
12// Defaults: || vs ??
13const volume = 0;
14console.log(volume || 50); // 50 - wrong, 0 was valid
15console.log(volume ?? 50); // 0 - correct
16
17// Explicit emptiness checks
18const list = [];
19console.log(list ? "truthy" : "falsy", list.length === 0 ? "empty" : "has items"); // truthy empty
20
21// Real booleans for APIs that need them
22const isDisabled = !!"";
23console.log(isDisabled, typeof isDisabled); // false "boolean"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app