Common Pitfalls with 0 and Empty Strings
You'll learn: Why using || for default values can unexpectedly replace valid zeros and empty strings.
The Hidden Bug
You've learned that || returns the first truthy value, making it seem perfect for default values. But here's the catch: both 0 and '' (empty string) are falsy. This means || will skip over them even when they're legitimate values you want to keep.
The Problem in Action
let score = 0;
let displayScore = score || 100;
console.log(displayScore); // 100 — whoops! We wanted 0!
let username = '';
let greeting = username || 'Guest';
console.log(greeting); // "Guest" — but maybe empty string was intentional!
let items = 0;
let message = items || 'No items';
console.log(message); // "No items" — lost the actual count!
In each case, || treated a valid value (0 or '') as "missing" and replaced it with the default. This is rarely what you want.
Think Before Using ||
The || operator is great for handling null or undefined, but dangerous when 0 or '' are valid inputs:
let age = null;
let displayAge = age || 18; // ✓ Works fine
let count = 0;
let displayCount = count || 1; // ✗ Bug! Replaces valid 0
The Analogy
Imagine a form where leaving a field blank triggers "N/A", but intentionally typing "0" also triggers "N/A". The system can't tell the difference between "nothing entered" and "zero entered" — both look empty to it.
Key Takeaway: The || operator treats 0 and '' as falsy and will replace them with defaults, causing subtle bugs when these are actually valid values you need to preserve.