AI Hints
Home›JavaScript Tutorial›More Decisions
JavaScript · Lesson 23 of 138

The Ternary Operator

A one-line if.

⏱ 2 min read▶ Video at 27:28🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Sometimes you just want to pick between two values, depending on a condition. Writing a whole if else for that feels long. The ternary operator does it in one line.

The Ternary Operator
From the video: The Ternary Operator
  • Pick between two values
  • if else feels long
  • One line

Condition, question mark, colon

Write the condition, then a question mark, then the value if it's true, then a colon, then the value if it's false. It's an expression, so you can store the result, or put it inside a template literal. Run it.

app.jsjavascript
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status);

const items = 1;
console.log(`You have ${items} ${items === 1 ? "item" : "items"}.`);
Output
adult
You have 1 item.

Keep it simple

Ternaries are great for short, simple choices. But don't nest them inside each other. That quickly becomes very hard to read. If there are more than two choices, use if and else if instead.

keyvalue
cond ? a : ba if true, else b
An expressionstore or insert it
Good forshort choices
Avoidnesting them

Ternaries in practice

Ternaries are great inside template literals, and for picking between two small values. Here we pick a label for each score in a loop. But when there are more than two choices, nested ternaries get hard to read, and an if else chain is clearer. Run it.

app.jsjavascript
const scores = [92, 45, 70];

for (const s of scores) {
  const result = s >= 50 ? "pass" : "fail";
  const icon = s >= 90 ? "(top score)" : "";
  console.log(`${s}: ${result} ${icon}`);
}
Output
92: pass (top score)
45: fail
70: pass

Summary

The ternary operator picks between two values in one line. Keep it for simple choices. Next, switch, for many exact cases.

Key takeaways
  • cond ? a : b
  • Great in templates
  • Don't nest
Next up: switch — many exact cases