What are truthy and falsy values in JavaScript?
When a value is used in a condition, JavaScript converts it to a boolean. Only eight values become false: false, 0, -0, 0n, empty string, null, undefined and NaN. Everything else, including [] and {}, is truthy.
Explain it simply
An if statement only understands yes or no. When you give it something else, like a number or a string, JavaScript quietly asks, "does this count as yes?" Values that count as yes are truthy; values that count as no are falsy.
The falsy list is short, so memorise it:
false, 0, -0, 0n, "" (empty string), null, undefined, NaN
Everything else is truthy. That includes some surprises: "0", "false", " " (a space), [] and {}.
Example
console.log(Boolean("")); // Output: false
console.log(Boolean("0")); // Output: true
console.log(Boolean(" ")); // Output: true
console.log(Boolean([])); // Output: true
console.log(Boolean({})); // Output: true
console.log(Boolean(0n)); // Output: false
const cart = [];
if (cart) {
console.log("cart exists"); // Output: cart exists
}
if (cart.length) {
console.log("has items"); // not printed
}To check whether an array has items, test cart.length, not cart.
What to say in the interview
"In a boolean context, values are converted with ToBoolean. Only eight values are falsy: false, 0, -0, 0n, the empty string, null, undefined and NaN. Everything else is truthy, including empty arrays, empty objects and the string '0'. That's why I check array.length for emptiness, and why I use ?? instead of || when 0 or an empty string is a valid value."
Common mistakes
- Expecting an empty array or empty object to be falsy.
- Writing
price || 100when a price of0is valid;0gets replaced by100.