The ternary
JavaScript · Unit 2: Conditionals
- Full plan
- JavaScript
- 10 exercises
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. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
People 60 or older pay 11; everyone else pays 15. Fill in the ternary.
4. Multiple choice
When is a ternary a better fit than an
if?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. Complete the code
With 50 or more the shipping is free; if not, it costs 8. Fill in the condition.
7. Predict the output
What does this code print?
8. Predict the output
What does this code print?
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. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.