JavaScript Ternary Operator
Table of Contents + −
In the previous lesson, we learned how to choose between many options with a switch statement. Now let’s learn the ternary operator, a short one-line way to write a simple if/else that produces a value.
❓ What is the Ternary Operator?
The ternary operator is the shortest way to choose between two values based on a condition. It checks a condition, and gives back one value if the condition is true and another value if it is false.
It is the only operator in JavaScript that takes three parts, which is where the name “ternary” comes from.
🧱 The Syntax
The ternary operator uses a question mark and a colon to separate its three parts.
condition ? valueIfTrue : valueIfFalse;This skeleton shows the three parts in order:
conditionis the test that comes first, before the?.- The
?introduces the value to use when the condition is true. - The
:separates that from the value to use when the condition is false.
| Part | Meaning |
condition | An expression that is either true or false |
? valueIfTrue | The value used when the condition is true |
: valueIfFalse | The value used when the condition is false |
Here is a simple example that decides whether someone is allowed in:
const age = 20;const access = age >= 18 ? "Allowed" : "Denied";
console.log(access); // "Allowed"The condition age >= 18 is true, so access gets the value "Allowed". If age were less than 18, access would be "Denied".
🔁 Comparing it to if/else
The ternary operator does the same job as a simple if/else, just in one line. Here is the same decision written the long way.
const age = 20;let access;
if (age >= 18) { access = "Allowed";} else { access = "Denied";}
console.log(access); // "Allowed"Let’s walk through what this longer version does:
- We declare
accesswithletbut leave it empty, because we don’t know its value yet. - The
ifchecksage >= 18, which is true, soaccessis set to"Allowed". - The
elsebranch would setaccessto"Denied", but it never runs here.
And here it is again with the ternary operator:
const age = 20;const access = age >= 18 ? "Allowed" : "Denied";
console.log(access); // "Allowed"Both versions give the same result. The ternary is shorter and lets us use const, because we assign the value once instead of declaring it empty and filling it in later.
When to reach for it
Use the ternary operator when you want to pick between two values. For
branches that run several statements, a regular if/else is clearer.
🏷️ A Practical Example
The ternary operator shines when we want to choose a message or label to show. Here we pick a greeting based on whether a user is logged in.
const isLoggedIn = true;const message = isLoggedIn ? "Welcome back!" : "Please sign in";
console.log(message); // "Welcome back!"Here’s what each line does:
isLoggedInis set totrue, so the condition is already true.- The ternary reads
isLoggedInand picks"Welcome back!"formessage. - If
isLoggedInwerefalse,messagewould be"Please sign in"instead.
It also works nicely right inside a template string, so we can build text on the fly:
const itemCount = 1;const label = `You have ${itemCount} item${itemCount === 1 ? "" : "s"}`;
console.log(label); // "You have 1 item"The condition itemCount === 1 decides whether we add an "s", so the word stays grammatically correct.
🪶 Keep it Simple
The ternary operator is at its best when it stays short and easy to read on a single line. It is possible to nest one ternary inside another, but that quickly becomes hard to follow.
// ❌ Hard to readconst result = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "F";This single line chains three ternaries together: it checks score > 90, and if that is false it falls through to score > 80, then score > 70, and finally "F". Each : hands off to the next test, which is why the line is so hard to trace.
When a decision has more than two outcomes, a regular if/else or a switch statement reads much better.
// ✅ Clearerlet grade;if (score > 90) { grade = "A";} else if (score > 80) { grade = "B";} else { grade = "C";}This version spells out the same logic on separate lines:
- The
ifchecksscore > 90first and setsgradeto"A"when it matches. - The
else ifchecksscore > 80only when the first test fails. - The final
elsecatches every remaining score and setsgradeto"C".
Avoid deep nesting
A ternary inside another ternary is hard to read and easy to get wrong. If you
feel the urge to nest, switch to an if/else instead.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
| Nesting ternaries too deeply | The code becomes hard to read and debug | Use if/else or switch for more than two outcomes |
| Using it to run actions instead of return a value | a ? doThis() : doThat() is confusing as a statement | Use a ternary only to choose a value; use if for actions |
| Forgetting the colon | age >= 18 ? "Allowed" is a syntax error | Always include both ? and : with two values |
🔧 Try It Yourself!
- Create an
agevariable and use a ternary to setaccessto"Allowed"or"Denied". - Make an
isLoggedInvariable and pick a welcome message with a ternary. - Use a ternary inside a template string to print
"1 item"or"3 items"correctly. - Rewrite one of your ternaries as a full
if/elseblock and confirm the result is the same.
🧩 What You’ve Learned
- ✅ The ternary operator is a one-line way to choose between two values
- ✅ Its syntax is
condition ? valueIfTrue : valueIfFalse - ✅ It does the same job as a simple
if/else, but returns a value - ✅ It works well for picking a message or label to display
- ✅ Keep it simple and avoid nesting ternaries inside one another
🚀 What’s Next?
Now that we can make decisions, let’s learn how to repeat actions. Let’s continue to for Loop.