Course contentsShow
← React
Lesson 136 of 2,3964. Conditional Rendering in JSXFree lesson

Boolean Coercion Mistakes with &&

Learn why `array.length && <Component />` can render `0` instead of nothing, and how to fix it with explicit checks.

Boolean Coercion Mistakes with &&

What you'll learn: Why certain "truthy" values like array.length can render visible numbers instead of nothing, breaking your conditional logic.


The Sneaky Zero Problem

You've learned that && works by evaluating the left side for truthiness. If truthy, React renders the right side. If falsy, React renders... the left side's value.

Here's the trap: JavaScript considers 0 falsy, but React renders 0 as visible text.

const items = [];

return (
  <div>
    {items.length && <p>You have items!</p>}
  </div>
);
// Renders: 0

Why? Because items.length is 0, which is falsy in JavaScript. The && operator returns the left operand when it's falsy. React then renders that 0 to the screen.

The Fix: Explicit Boolean Checks

Always convert your condition to an actual boolean:

// Option 1: Explicit comparison
{items.length > 0 && <p>You have items!</p>}

// Option 2: Double negation (!! pattern)
{!!items.length && <p>You have items!</p>}

Both ensure the left side evaluates to true or false, not 0.

Other Danger Zones

This mistake happens with any numeric value that could be 0:

{count && <Badge />}          // Renders 0 when count is 0
{price && <PriceTag />}       // Renders 0 when price is 0
{offset && <Spacer />}        // Renders 0 when offset is 0

Empty strings ("") are also falsy and render nothing, but 0 is the most common footgun because array lengths are so frequently used in conditionals.

Key Takeaway: Always use explicit boolean checks (value > 0, !!value, value !== 0) with && to avoid accidentally rendering 0 to the screen.