The ternary operator picks one of two values based on a condition. It is the only JavaScript operator with three parts.
condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // → adult
It is a short form of this if/else:
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
The big difference: the ternary is an expression, so it produces a value you can use directly. That makes it handy inside template literals and function calls.
const items = 3;
console.log(`You have ${items} ${items === 1 ? "item" : "items"}`); // → You have 3 items
const isOnline = false;
console.log(isOnline ? "Online" : "Offline"); // → Offline
Updating the page
<button id="toggle">Toggle</button>
<p id="state">Off</p>
<script>
let on = false;
document.querySelector("#toggle").addEventListener("click", () => {
on = !on;
document.querySelector("#state").textContent = on ? "On" : "Off";
});
</script>
Chaining (use with care)
You can chain ternaries, but readability drops fast.
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";
Two levels are fine. Beyond that, an if / else if chain (see else if) is easier to read.
When not to use it
- When you need to do several things in each branch. Use
if. - When you are not using the result.
x > 5 ? doThis() : doThat();works, but a plainifsays what you mean.
A readability test
if.