Short-Circuit Evaluation: && and ||
What you'll learn: How to use && and || operators inside JSX to conditionally show content or provide fallback values.
The Core Idea
JavaScript's logical operators don't just return true or false—they return one of the actual values being compared and "short-circuit" (stop evaluating) as soon as the result is determined. React leverages this behavior to let you conditionally render elements or provide default values directly inside JSX.
The && Operator: Conditional Display
The && operator evaluates left-to-right and stops at the first "falsy" value. If the left side is truthy, it returns the right side:
function Greeting({ username }) {
return (
<div>
<h1>Welcome!</h1>
{username && <p>Hello, {username}!</p>}
</div>
);
}
How it works: If username exists (truthy), React renders the <p> tag. If username is null, undefined, or an empty string (falsy), nothing renders.
Think of it like: "If the first thing is true, show the second thing."
The || Operator: Default Values
The || operator stops at the first "truthy" value:
function Profile({ name }) {
return <h2>{name || "Anonymous User"}</h2>;
}
If name is empty or undefined, it displays "Anonymous User" instead.
Common Pitfall
Be careful with numbers! {count && <span>{count} items</span>} will render 0 when count is zero (because 0 is falsy but still renders). Use explicit comparison: {count > 0 && ...} instead.
Key Takeaway: Use && to conditionally show elements when a value is truthy, and || to provide fallback values when a value is falsy—both work because JavaScript short-circuits evaluation and returns actual values, not just booleans.