Skip to the content

The ternary

JavaScript · Unit 2: Conditionals

The ternary picks between two values in a single line: condition ? value1 : value2.

It reads "is it met? then value1, if not value2". Unlike the if, it hands back a value you can store.

let age = 8;
let pay = age < 12 ? 9 : 15;
console.log(pay);

Prints

9

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    People 60 or older pay 11; everyone else pays 15. Fill in the ternary.

  4. 4. Multiple choice

    When is a ternary a better fit than an if?

  5. 5. Find the bug

    People 60 or older pay 11 and everyone else pays 15. This person is 70. Which line has the error?

  6. 6. Complete the code

    With 50 or more the shipping is free; if not, it costs 8. Fill in the condition.

  7. 7. Predict the output

    What does this code print?

  8. 8. Predict the output

    What does this code print?

  9. 9. Put the lines in order

    Put the function in order. Shipping is free with 50 or more, and if not it costs 8.

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →