Sometimes you just want to pick between two values based on a condition. Writing a full if/else for that feels like a lot of typing:
const age = 20;
let message;
if (age >= 18) {
message = "adult";
} else {
message = "minor";
}
console.log(message);
It prints
adult
JavaScript has a shortcut for exactly this situation. It's called the ternary operator (because it has three parts), and it looks like this:
condition ? valueIfTrue : valueIfFalse
So the code above becomes:
const age = 20;
const message = age >= 18 ? "adult" : "minor";
console.log(message);
It prints
adult
Read it like a question: "Is age at least 18? If yes, "adult". Otherwise, "minor"." The ternary is great inside template literals too:
const itemCount = 1;
console.log(`You have ${itemCount} ${itemCount === 1 ? "item" : "items"} in your cart.`);
const lives = 0;
console.log(lives > 0 ? "Keep playing!" : "GAME OVER 💀");
It prints
You have 1 item in your cart. GAME OVER 💀
Ternaries are perfect for simple "this or that" choices. But you can chain them together, and things get ugly fast: a ? b : c ? d : e ? f : g. Yikes. If you find yourself doing that, go back to a normal if/else if. Readable code beats clever code every single time.