Glossary / Truthiness

Truthiness

Truthiness is the Boolean conversion JavaScript applies in conditions and logical operators. The falsy values are exactly false, 0, -0, 0n, "", null, undefined, and NaN; every other value is truthy. That includes empty arrays, empty objects, the string "0", and the string "false".

Boolean conversion and logical operators

Boolean([]);       // true
Boolean("");       // false
Boolean("false"); // true

if, while, !, and the first operand of && and || use truthiness. Logical operators return operand values rather than necessarily returning booleans:

Therefore value || fallback is not equivalent to “use fallback if missing.” It also replaces valid values such as zero, false, and empty string. Use ?? when only nullish values indicate absence, or an explicit condition when the domain has a more specific rule.

Practical pitfalls

Never validate user input merely by checking truthiness. The text "0" is truthy; numeric zero is falsy; whitespace-only strings are truthy. Convert and validate input according to its schema. When a function expects a boolean, normalize deliberately or document accepted truthy/falsy input. Be careful using array.length && ...: the result can be 0 rather than false, which is fine in a condition but may leak into rendering or data.

Interview questions

  1. Is an empty array truthy? Yes; all objects are truthy.
  2. List the falsy values. False, positive/negative zero, 0n, empty string, null, undefined, and NaN.
  3. What does || return? One of its operands, not necessarily a Boolean.
  4. When prefer ?? over ||? When zero, false, or empty string should be preserved as legitimate values.

References