Control flow · Lesson 11 of 45
switch and the ternary operator
Shorter alternatives for many choices or just two.
7 minutes3 games
The ternary is a one-line condition: condition ? ifTrue : ifFalse. Perfect for choosing between two values.
JavaScript
const stock = 0
const label = stock > 0 ? "In stock" : "Sold out"
console.log(label)
const items = 1
console.log(`${items} ${items === 1 ? "item" : "items"}`)switch
switch compares one value against several options (using ===). Each case needs a break, or execution falls into the next case. default runs if nothing matched.
JavaScript
const day = "fri"
switch (day) {
case "fri":
case "sat":
console.log("Weekend")
break
case "sun":
console.log("Back to work")
break
default:
console.log("Weekday")
}fri and sat share code: a case without a break falls through on purpose.
What's the output?
const n = 2
switch (n) {
case 1:
console.log("one")
case 2:
console.log("two")
case 3:
console.log("three")
}What will this code print?
Complete the code
Write the ternary: Pass for 50 or more, otherwise Fail.
const result = score >= 50 "Pass" "Fail"
Exercise
Use a ternary to print even or odd for n.
Expected output: odd
JavaScript
const n = 7
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.