Truthy and Falsy in JavaScript: What They Mean and How They Work
truthy values are those that are considered true in a boolean context, while falsy values are treated as false. Common falsy values include false, 0, "" (empty string), null, undefined, and NaN. Everything else is truthy.How It Works
JavaScript uses a simple rule when it needs to decide if a value means "true" or "false" in conditions like if statements. Instead of only accepting true or false, it treats some values as true (truthy) and others as false (falsy).
Think of it like a light switch: some things turn the switch on (truthy), and others turn it off (falsy). For example, the number 0 is like a switch off, but the number 1 is switch on. This helps JavaScript decide what to do without needing strict true or false values.
This behavior lets you write shorter code by using values directly in conditions without converting them first.
Example
This example shows how different values behave in an if condition to check if they are truthy or falsy.
const values = [false, 0, "", null, undefined, NaN, true, 1, "hello", [], {}]; values.forEach(value => { if (value) { console.log(`${JSON.stringify(value)} is truthy`); } else { console.log(`${JSON.stringify(value)} is falsy`); } });
When to Use
Knowing about truthy and falsy values helps you write cleaner and simpler code. You can use any value directly in conditions without converting it to true or false. For example, checking if a string is empty or not can be done by just using the string in an if statement.
This is useful in real-world cases like validating user input, controlling program flow, or toggling features based on variable states.
Key Points
- Falsy values in JavaScript are
false,0,"",null,undefined, andNaN. - All other values are truthy, including empty arrays
[]and objects{}. - Using truthy and falsy values lets you write shorter, more readable conditional code.
- Be careful with falsy values like
0or""when they are valid inputs but treated as false.