CodePark/ questions / Types & coercion
START PRACTICINGPRACTICE
Frontend question · JavaScript › Types & coercion

What are truthy and falsy values? List the falsy values.

A falsy value is one that becomes false when JavaScript needs a boolean. Every other value is truthy, which means it becomes true.

JavaScript needs a boolean in places like an if, &&, ||, ! and the ternary a ? b : c. There it converts the value automatically.

This is the complete list of falsy values:

  • false
  • 0 and -0
  • 0n (the BigInt zero)
  • '' (the empty string)
  • null
  • undefined
  • NaN

Browsers also have one old special case, document.all, which is falsy too.

Some values look false but are truthy: '0', 'false', ' ', [], {} and new Boolean(false). The reason is simple. Every non-empty string is truthy, and every object is truthy.

This causes real bugs:

  • if (arr) does not check for an empty array, because [] is truthy. Use if (arr.length).
  • count || 10 replaces a valid 0 with 10. Use count ?? 10, which only replaces null and undefined.
  • In a boolean context, JavaScript converts the value with its internal ToBoolean rule, which turns any value into true or false.
  • The falsy values are false, 0, -0, 0n, '', null, undefined and NaN.
  • All objects are truthy, including [] and {}.
  • || defaults replace valid falsy values like 0. Use ?? instead.