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:
false0and-00n(the BigInt zero)''(the empty string)nullundefinedNaN
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. Useif (arr.length).count || 10replaces a valid0with10. Usecount ?? 10, which only replacesnullandundefined.
- In a boolean context, JavaScript converts the value with its internal ToBoolean rule, which turns any value into
trueorfalse. - The falsy values are
false,0,-0,0n,'',null,undefinedandNaN. - All objects are truthy, including
[]and{}. ||defaults replace valid falsy values like0. Use??instead.
Read more
- Falsy (MDN) (https://developer.mozilla.org/en-US/docs/Glossary/Falsy)developer.mozilla.org
- Truthy (MDN) (https://developer.mozilla.org/en-US/docs/Glossary/Truthy)developer.mozilla.org