🎓 A1Learner
🔍
0 of 50 lessons completed

Ternary Expressions

A ternary expression chooses between two values in one line. The expression holds a condition, a question mark, a value, a colon, and a second value.

One of two greetings

The greeting changes with the loggedIn value.

const loggedIn = true;
return <p>{loggedIn ? 'Welcome back.' : 'Please log in.'}</p>;

One of two labels

Zero tasks show one label and more tasks show another.

const count = 0;
return <p>{count === 0 ? 'No tasks.' : 'Tasks wait.'}</p>;

Example

import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>{count === 0 ? 'No tasks.' : 'Tasks wait.'}</p>
      <button onClick={() => setCount(count + 1)}>Add a task</button>
    </div>
  );
}

Key points

  • The first value is what shows when the test passes.
  • The second value is what shows when the test fails.
  • A ternary expression fits inside JSX curly braces.
  • A ternary expression keeps both branches short.

In this example, the count state value starts at zero. The ternary expression tests count against zero. Zero shows No tasks. A click adds one to count. The next render shows Tasks wait.

Note

Long branches belong in an if statement instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line shows Done when done is true and Waiting when done is false?