JavaScript Ternary Operator

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.

ternary-operator.js
condition ? valueIfTrue : valueIfFalse;

This skeleton shows the three parts in order:

  • condition is 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:

ternary-operator.js
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.

ternary-operator.js
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 access with let but leave it empty, because we don’t know its value yet.
  • The if checks age >= 18, which is true, so access is set to "Allowed".
  • The else branch would set access to "Denied", but it never runs here.

And here it is again with the ternary operator:

ternary-operator.js
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.

ternary-operator.js
const isLoggedIn = true;
const message = isLoggedIn ? "Welcome back!" : "Please sign in";
console.log(message); // "Welcome back!"

Here’s what each line does:

  • isLoggedIn is set to true, so the condition is already true.
  • The ternary reads isLoggedIn and picks "Welcome back!" for message.
  • If isLoggedIn were false, message would be "Please sign in" instead.

It also works nicely right inside a template string, so we can build text on the fly:

ternary-operator.js
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.

ternary-operator.js
// ❌ Hard to read
const 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.

ternary-operator.js
// ✅ Clearer
let 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 if checks score > 90 first and sets grade to "A" when it matches.
  • The else if checks score > 80 only when the first test fails.
  • The final else catches every remaining score and sets grade to "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!

  1. Create an age variable and use a ternary to set access to "Allowed" or "Denied".
  2. Make an isLoggedIn variable and pick a welcome message with a ternary.
  3. Use a ternary inside a template string to print "1 item" or "3 items" correctly.
  4. Rewrite one of your ternaries as a full if/else block 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.

Share & Connect