This or That

A page often shows either one thing or another: a ticket is free or has a price, a night is the opening night or the closing night. With if and else, you'd need a variable:

let label;
if (band.day === "Friday") {
    label = "Opening night";
} else {
    label = "Closing night";
}

JavaScript has a shorter way to write this, the conditional operator:

const label = band.day === "Friday" ? "Opening night" : "Closing night";

Read it as a question: is band.day === "Friday"? If yes, the result is the value after ?; otherwise, it's the value after :. It has three parts, so it's also called the ternary operator. And unlike if, it's an expression: it gives a value. So it can go where if can't, into JSX's curly braces:

<p>{band.day === "Friday" ? "Opening night" : "Closing night"}</p>

It can choose an attribute too, for example the classes of an element. className can hold several classes, separated by spaces:

<article className={band.stage === "Main Stage" ? "card big" : "card"}>

And it can choose between two elements: {band.headliner ? <strong>{band.name}</strong> : band.name}. It's good for short choices between two values. When each branch is several lines of JSX, an if with an early return is easier to read.

A typical mistake is to leave out the part after :. The conditional operator always needs both values. For "this or nothing", there's a shorter way, which comes in the next exercise.

Instructions

Give each card a second class by its day: friday for Friday's bands and saturday for Saturday's, which colors its edge. Keep its class card.

When it rains, only the Tent has a roof. Under the stage and time, add a paragraph to each card that says Indoors for bands in the Tent and Outdoors for the others.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/11

Next