Course contentsShow
← TypeScript
Lesson 210 of 1,7965. Type Narrowing FundamentalsFree lesson

Common Truthiness Mistakes

Pitfalls when valid values like 0 or empty string are falsy, and strategies to avoid bugs.

Common Truthiness Mistakes

You'll learn: How truthiness checking can accidentally treat valid values like 0 or "" as errors, and how to write safer conditions.

The Hidden Danger of Falsy Valid Values

Truthiness narrowing is powerful, but it comes with a classic trap: not all falsy values are invalid. In JavaScript and TypeScript, these values are falsy:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

The problem? Sometimes 0 is a perfectly valid number. Sometimes "" is a legitimate empty string. When you use truthiness checks blindly, you treat these valid values as "bad" values.

The Classic Bug

function displayScore(score: number | null) {
  if (score) {
    console.log(`Your score: ${score}`);
  } else {
    console.log("No score available");
  }
}

displayScore(0); // Bug! Prints "No score available" 
displayScore(100); // Works: "Your score: 100"

A score of 0 is valid, but the truthiness check treats it like null!

The Fix: Be Explicit

Instead of relying on truthiness, check exactly what you care about:

function displayScore(score: number | null) {
  if (score !== null) {
    console.log(`Your score: ${score}`);
  } else {
    console.log("No score available");
  }
}

displayScore(0); // Correct: "Your score: 0"

Same issue with empty strings:

function greet(name: string | undefined) {
  // Wrong: treats "" as missing
  if (name) { /* ... */ }
  
  // Right: only checks for undefined
  if (name !== undefined) { /* ... */ }
}

Key Takeaway: Use truthiness narrowing only when ALL falsy values mean the same thing. When 0, "", or false are valid, use explicit comparisons like !== null or !== undefined instead.