Sub topic 11
Showing or hiding with && and the 0 pitfall
This chapter covers the && operator as a way to show or hide part of a component. It explains why && can print a stray 0 on screen and how to prevent that. It assumes you know JavaScript truthiness, function components, props, JSX expressions, and the earlier chapters on if and the ternary operator.
The idea: show it or show nothing
Sometimes a component has one optional piece of output. A badge appears only when there are unread messages. A warning appears only when a form is invalid. There is no "else" branch, because the other case is simply nothing.
A ternary can express this, but it needs an empty second branch:
{isAdmin ? <AdminLink /> : null}The logical AND operator (&&) is shorter for the same job:
{isAdmin && <AdminLink />}Read it as "if isAdmin is true, show <AdminLink />". When the left side is false, nothing is shown.
How && works in JavaScript
React does not give && any special meaning. It is the ordinary JavaScript operator, and it evaluates like this:
- Evaluate the left-hand side.
- If it is falsy, stop and return that left-hand value, unchanged.
- If it is truthy, evaluate the right-hand side and return that.
&& returns one of its operands. It does not return true or false. This is how the shortcut works. It is also where the pitfall comes from.
console.log(true && 'shown'); // 'shown'
console.log(false && 'shown'); // false
console.log(0 && 'shown'); // 0
console.log('' && 'shown'); // ''
console.log(null && 'shown'); // nullThe right-hand side is only evaluated when the left side is truthy. This is called short-circuiting. It means user && user.name does not throw when user is null.
What React does with each result
JSX renders whatever the expression returns. React treats different values differently:
| Value returned | What React renders |
|---|---|
| `true` or `false` | Nothing |
| `null` or `undefined` | Nothing |
| `''` (empty string) | Nothing visible |
| A number, such as `0` or `42` | The number as text |
| A string, such as `'hi'` | The text |
| A React element | The element |
The key row is the number row. false, null, and undefined are skipped, so && with a boolean on the left works well. A number is not skipped, and that includes 0.
The 0 pitfall
Suppose an inbox shows an unread badge:
function Inbox({ unreadCount }) {
return (
<div>
{/* Renders the number 0 when unreadCount is 0 */}
{unreadCount && <span>{unreadCount} unread</span>}
{/* Renders nothing when unreadCount is 0 */}
{unreadCount > 0 && <span>{unreadCount} unread</span>}
</div>
);
}Trace the first line when unreadCount is 0:
0is falsy, so&&stops and returns the left-hand value,0.- JSX receives the number
0. - React renders numbers, so a literal
0appears on the page.
The author expected an empty space. Users see a lone 0 instead. With any positive count the code works, so the bug often escapes testing and shows up only in the empty state.
The second line avoids the problem. The comparison unreadCount > 0 always produces a boolean. When it is false, && returns false, and React renders nothing.
Fixes for the pitfall
There are three common ways to make the left side a real boolean.
Compare explicitly. This is usually the clearest, because it states the condition you mean:
{items.length > 0 && <ItemList items={items} />}Convert with Boolean() or !!:
{Boolean(unreadCount) && <span>{unreadCount} unread</span>}
{!!unreadCount && <span>{unreadCount} unread</span>}Switch to a ternary with null, which does not depend on the left value's type:
{unreadCount ? <span>{unreadCount} unread</span> : null}This last form has a gap too. If unreadCount is NaN, it is falsy, so the ternary returns null. But with &&, NaN && ... returns NaN, and React renders the text "NaN". Explicit comparisons avoid this as well, because NaN > 0 is false.
Other falsy values
The pitfall is specific to numbers. Here is how each falsy value behaves on the left of &&:
| Left-hand value | `&&` returns | React renders |
|---|---|---|
| `false` | `false` | Nothing |
| `null` | `null` | Nothing |
| `undefined` | `undefined` | Nothing |
| `''` | `''` | Nothing visible |
| `0` | `0` | `0` |
| `NaN` | `NaN` | `NaN` |
An empty string is safe in practice because it renders as empty text. The two risky values are 0 and NaN. Both usually come from numeric data such as array lengths, counts, prices, and quantities. When the left side is a number, add a comparison.
Edge case: undefined from a component
Do not confuse the left-hand value with what a component returns. In current React versions, a component may return undefined, and it renders nothing. Still, returning null explicitly makes the intent clear.
A related error is using && to guard against a missing array:
function Tags({ tags }) {
return (
<ul>
{tags && tags.map(tag => <li key={tag}>{tag}</li>)}
</ul>
);
}This works when tags is undefined or null, because both render nothing. It is safe here because tags is an array or nullish, never a number. The pitfall only appears when a numeric value can be on the left.
Putting && in a larger component
This component from the plan combines filtering, an empty state, and && in one place:
import { useState } from 'react';
function Todos({ initialTodos }) {
const [todos, setTodos] = useState(initialTodos);
const [hideDone, setHideDone] = useState(false);
const visible = hideDone ? todos.filter(todo => !todo.done) : todos;
function remove(id) {
setTodos(todos.filter(todo => todo.id !== id));
}
return (
<>
<label>
<input
type="checkbox"
checked={hideDone}
onChange={e => setHideDone(e.target.checked)}
/>
Hide completed
</label>
{visible.length === 0 ? (
<p>Nothing to show.</p>
) : (
<ul>
{visible.map(todo => (
<li key={todo.id}>
{todo.title}
{todo.done && <span> (done)</span>}
<button onClick={() => remove(todo.id)}>Remove</button>
</li>
))}
</ul>
)}
</>
);
}Two choices are worth noting:
- The "(done)" badge uses
&&because there is no alternative output.todo.doneis a boolean, so the pitfall does not apply. - The empty state uses a ternary because there are two real outputs: a message or a list.
If you wanted to show a count of remaining items only when there are some, you would write remaining > 0 && <p>{remaining} left</p>, not remaining && ....
When not to use &&
&& is best for one optional element. Avoid it in these cases:
- Two outputs. Use a ternary or an
ifwith an early return. Writingcond && <A />followed by!cond && <B />repeats the condition and invites mistakes. - Long or nested conditions. Chained
&&inside JSX gets hard to read. Compute a named boolean above thereturn, such asconst showBadge = unreadCount > 0;, then write{showBadge && <Badge />}. - Nested ternaries combined with
&&. Move the logic into variables or small components.
Common errors
- A stray
0on screen. The left side is a number. Add> 0or convert to a boolean. Cannot read properties of undefined. The guard is on the wrong value. Checkuser && user.address && user.address.city, or use optional chaining:user?.address?.city.- Putting
&&outside the braces. In JSX, text and elements are children.&&is JavaScript, so it must sit inside{ }. - Wrapping the right side incorrectly. Multi-line JSX on the right does not need extra parentheses for correctness, but parentheses keep formatting readable.
Exercise
A shopping cart component renders {items.length && <CartSummary items={items} />}. With an empty cart, the page shows a 0 where nothing should appear. Explain why, and write the fix.
Show answer
When items.length is 0, it is falsy, so && returns the left-hand value 0 without evaluating <CartSummary />. React renders numbers as text, so 0 appears. Make the left side a boolean: {items.length > 0 && <CartSummary items={items} />}. A ternary also works: {items.length ? <CartSummary items={items} /> : null}.
Exercise
Which of these left-hand values can cause visible output when used with && in JSX: false, null, undefined, '', 0, NaN? Which fix handles all of them?
Show answer
0 and NaN render as text, because React renders numbers. false, null, undefined, and '' render nothing visible. Using an explicit boolean comparison, such as count > 0, handles all of them, because the left side is then always true or false.