Course contentsShow
← React
Lesson 110 of 2,3964. Conditional Rendering in JSXFree lesson

The && Operator in JSX: Basic Syntax

Learn how JavaScript's logical AND operator renders elements conditionally based on truthy values.

The && Operator in JSX: Basic Syntax

You'll learn how to conditionally render JSX elements using JavaScript's logical AND operator based on whether a value is truthy.

The Core Idea

In JavaScript, the && operator evaluates the left side first. If it's truthy, it returns the right side. If it's falsy, it returns the left side (which React often renders as nothing). This creates a simple pattern: {condition && <Element />} means "if condition is true, show Element."

How It Works in JSX

When you write this in your component:

function Greeting() {
  const isLoggedIn = true;
  
  return (
    <div>
      <h1>Welcome</h1>
      {isLoggedIn && <p>You are logged in!</p>}
    </div>
  );
}

React evaluates isLoggedIn && <p>You are logged in!</p>. Since isLoggedIn is true (truthy), the expression returns the <p> element, and it renders.

If isLoggedIn were false:

{false && <p>You are logged in!</p>}

The expression returns false, which React renders as nothing (remember: booleans render invisibly in JSX).

Think of It Like a Gate

Imagine a bouncer at a club door. The left side of && is the bouncer's decision. If they say "yes" (truthy), the person (right side JSX) gets in. If they say "no" (falsy), nobody passes through — nothing renders.

Common Pattern

{messages.length > 0 && <span>You have {messages.length} messages</span>}

Only show the message count if there are actually messages.

Key Takeaway: Use {condition && <JSX>} to render elements only when the condition is truthy — it's the simplest form of conditional rendering in React.