Explicit Comparisons Over Implicit Truthiness
You'll learn why writing conditions like array.length > 0 is safer than relying on array.length alone when rendering conditionally.
The Problem with Implicit Truthiness
In the previous lesson, you learned about the zero trap: when you write array.length && <Component />, an empty array (length 0) renders the number 0 to the screen instead of rendering nothing. This happens because 0 is falsy in JavaScript but still gets displayed in JSX.
The root issue is implicit truthiness — relying on JavaScript's automatic truthy/falsy conversion. While convenient, it creates subtle bugs.
The Explicit Solution
Instead of letting JavaScript decide what's "truthy enough," spell out exactly what you mean:
// ❌ Implicit — risky with numbers
{items.length && <ItemList items={items} />}
// ✅ Explicit — clear intent, safe behavior
{items.length > 0 && <ItemList items={items} />}
The explicit comparison items.length > 0 returns a boolean (true or false). Since both true and false render as nothing in JSX, you'll never accidentally display unwanted values.
When This Matters Most
Use explicit comparisons whenever your condition involves:
- Numbers:
count > 0,price >= 10 - Strings:
name.length > 0orname !== "" - Unclear intent: When another developer might misunderstand your condition
Boolean variables are already explicit: isLoggedIn && <Dashboard /> is fine because isLoggedIn is clearly true or false.
The Clarity Principle
Explicit code is self-documenting. When you write > 0, future readers (including yourself) instantly understand you're checking for a non-empty collection. With just array.length, readers must remember JavaScript's truthiness rules.
Key Takeaway: Write array.length > 0 && <Component /> instead of array.length && <Component /> to avoid rendering unexpected values and make your intent crystal clear.