Why does {count && <Badge />} show 0 on the screen when count is zero?
The && operator returns the left side when it is falsy, and React renders the number 0. Convert to a boolean first: {count > 0 && <Badge />}, or use a ternary.
Explain it simply
In JavaScript 0 && "x" evaluates to 0, not false. React skips false, null and undefined, but it prints the number 0. So a cart count of zero shows a stray 0 beside your icon.
Make the left side a real boolean: count > 0 && ..., or Boolean(count) && ..., or use a ternary count ? <Badge /> : null.
The same happens with an empty string in some cases and with NaN, which also prints.
This bug shows up most with lists: items.length && <List /> prints 0 when the array is empty. It is also a classic interview trick question, because the code looks correct and the output is surprising. The safe habit is to never put a bare number on the left of && in JSX.
Example
function Cart({ count }) {
return (
<div>
{count && <span className="badge">{count}</span>} {/* prints 0 */}
{count > 0 && <span className="badge">{count}</span>} {/* prints nothing */}
</div>
);
}What to say in the interview
"React renders numbers, including 0, so the left side of && must be a boolean. I write count > 0 && ... or use a ternary. false, null and undefined render nothing, but 0 and NaN do."
Common mistakes
- Using array.length && ... for lists.