0
0
JavascriptConceptBeginner · 3 min read

Truthy and Falsy in JavaScript: What They Mean and How They Work

In JavaScript, 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.

javascript
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`);
  }
});
Output
"false" is falsy 0 is falsy "" is falsy null is falsy undefined is falsy NaN is falsy true is truthy 1 is truthy "hello" is truthy [] is truthy {} is truthy
🎯

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, and NaN.
  • 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 0 or "" when they are valid inputs but treated as false.

Key Takeaways

Falsy values are treated as false in conditions; all others are truthy.
Falsy values include false, 0, empty string, null, undefined, and NaN.
Truthy values include non-empty strings, numbers other than 0, objects, and arrays.
Use truthy and falsy to write simpler conditional statements.
Watch out for valid data that might be falsy, like 0 or empty strings.