Handle zero and null correctly
Include optional content safely
Use logical AND when a piece of UI is optional and a boolean condition says whether to include it. JavaScript may return an operand rather than a boolean. React displays numbers as text, while boolean values and null do not produce visible child content. This distinction matters when a condition is a count.
function PickupNotice({ needsId }) { return ( <section> <h2>Pickup instructions</h2> {needsId && <p>Bring your identification.</p>} </section> );}
export default function App() { return <main><PickupNotice needsId /><PickupNotice needsId={false} /></main>;}Expected: two headings, but only the first section contains the identification instruction. When needsId is false, JavaScript does not evaluate the right operand and the resulting false is omitted from the visible output.
Avoid an accidental zero in the interface
function WaitingBadge({ count }) { return <section><h2>Waiting parcels</h2>{count && <p>{count} waiting</p>}</section>;}
export default function App() { return <main><WaitingBadge count={0} /><WaitingBadge count={2} /></main>;}Expected: the first section includes a stray 0 after its heading, and the second includes 2 waiting. The JSX is syntactically valid, but the first result is undesirable. JavaScript evaluates 0 && something to 0; React has not converted it into false.
function WaitingBadge({ count }) { if (count === null || count === undefined) { return <p>Waiting count unavailable.</p>; } if (count === 0) return null; return <p>{count} waiting</p>;}
export default function App() { const count = 0; return ( <main> <h1>Waiting parcels</h1> {count > 0 && <p>{count} waiting</p>} <WaitingBadge count={0} /> <WaitingBadge count={3} /> <WaitingBadge count={null} /> <WaitingBadge /> </main> );}Expected: the heading, 3 waiting, then two Waiting count unavailable paragraphs. The first expression has a boolean left operand, and the zero-count component returns null deliberately. The number contract is a nonnegative integer or missing value. Zero is known information; null and undefined represent missing information in this example. Do not treat unknown as zero unless the product requirement says so. Returning null does not itself mean the component has unmounted; a parent omitting the component entirely is a separate choice. This matters when you later add state.
Practice
Write a notice that shows a positive number of unread messages, hides the notice when the count is zero, and shows Count unavailable when the count is null or omitted. Check 0, 1, 5, null, and undefined.