Why && Works: Truthy/Falsy Evaluation
What you'll learn: How React decides whether to render the right side of && based on JavaScript's truthy/falsy rules.
The Core Mechanism
When you write {isLoggedIn && <WelcomeMessage />} in JSX, React doesn't magically "understand" conditionals. Instead, it relies on how JavaScript's && operator works:
JavaScript evaluates && from left to right and stops early:
- If the left side is falsy, JavaScript returns that falsy value and never looks at the right side
- If the left side is truthy, JavaScript continues and returns the right side's value
React then takes whatever JavaScript returned and decides what to render based on the rules you already learned: null, undefined, true, and false render as nothing.
Why This Works Perfectly for Conditional Rendering
Think of && as a gatekeeper checking IDs at a concert venue:
- Falsy left side (
false,0,null,undefined,"",NaN): The gatekeeper stops you. JavaScript returns the falsy value, React renders nothing. - Truthy left side (everything else): The gatekeeper waves you through. JavaScript returns the right side (your JSX component), and React renders it.
So {true && <Button />} returns <Button /> → React renders it.
But {false && <Button />} returns false → React renders nothing.
This is pure JavaScript behavior—React just renders whatever value the expression produces.
The Gotcha with 0
Here's the one trap: {count && <Message />} will render 0 on screen when count is 0, because 0 is falsy in boolean contexts but React renders numbers as text. Always use explicit comparisons: {count > 0 && <Message />}.
Key Takeaway: && works for conditional rendering because JavaScript short-circuits on falsy values, returning them directly, and React renders most falsy values as nothing—except numbers like 0.