Learn JavaScript · lesson 15 of 60 · about 8 minutes
Ternary and switch
Give each favourite language its own tip with switch, and pick between two values in one line with ? :.
What you'll learn
- Write a ternary expression
- Use switch with case and break
- Pick the right tool
A tip for every language
Sam wants a different tip for each favourite language. An else if for each one would mean writing fav === over and over. When you're checking one value against a list of exact answers, switch is neater.
The ternary operator
condition ? valueIfTrue : valueIfFalse picks one of two values. It's perfect for short either/or choices.
Ternary
const lives = 1;
const label = lives === 1 ? "life" : "lives";
console.log(`${lives} ${label} left`);Output
1 life leftswitch
switch compares one value against many exact cases. break stops it running into the next case. default catches everything else.
switch on a day
const day = "Sat";
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend");
break;
case "Mon":
console.log("Back to it");
break;
default:
console.log("Weekday");
}Output
WeekendA tip for the visitor's language
const fav = "Python";
let tip;
switch (fav) {
case "JavaScript":
tip = "You'll love making buttons work.";
break;
case "Python":
tip = "Python is great for automating boring jobs.";
break;
default:
tip = "Every language teaches you something new.";
}
document.querySelector("#tip").textContent = `Tip: ${tip}`;switch uses ===
Each case is compared with ===, so the type has to match too: case 3 never matches the text "3". Convert first if the value came from a box.
Tip
Forgetting break is the classic switch bug: the code falls through into the next case.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.