Javascript Ternary Operator Simplified

In JavaScript, we often use if...else statements to make decisions, but there's a shorter way to write simple conditions—it's called the ternary operator. It helps keep your code clean and compact, especially when making quick decisions inside one line of code.

What Is a Ternary Operator?

The ternary operator is a compact way to write a condition. It’s called “ternary” because it uses three parts: a condition, a result if true, and a result if false.

Syntax

javascript
1
          condition ? expressionIfTrue : expressionIfFalse;
        
  • The condition is something JavaScript will check (like age > 18)
  • If the condition is true, the first expression runs.
  • If it’s false, the second one runs.

Make sure it’s easy to read. If the condition or the results are too complex, it's better to use a regular if...else.

A Simple Example

Let’s say we want to check if someone is old enough to drive:

javascript
1
2
3
          let age = 18;
let canDrive = age >= 18 ? "You can drive" : "You can't drive";
console.log(canDrive); // Output: You can drive
        

If the age is 18 or more, canDrive will be "You can drive". Otherwise, it will be "You can't drive".

Since the age is 18, the condition age >= 18 is true, so the message will be: You can drive.

Rewriting if...else with a Ternary

Let’s see how you can rewrite a normal if...else using the ternary operator.

Using if...else

javascript
1
2
3
4
5
6
7
8
          let age = 18;
let canDrive;

if (age >= 18) {
  console.log(canDrive = "Yes");
} else {
  console.log(canDrive = "No");
}
        

Using ternary operator

javascript
1
2
3
4
          let age = 18;
let canDrive = age >= 18 ? "Yes" : "No";

console.log(canDrive)
        

Both versions do the same thing, but the second one is shorter and easier to read.

Nesting Ternary Operators (With Caution)

You can put one ternary inside another. But don’t go overboard — it can get messy fast.

javascript
1
2
3
4
5
6
7
          let score = 85;

let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" : "F";

console.log(grade);
        

This works, but it's better to use if...else for complex checks to keep your code clean.

When to Use the Ternary Operator

Use the ternary when:

  • You want to set a variable based on a simple condition.
  • You need a quick return value inside a function.
  • You’re working inside JSX (like in React) and want to show something based on a condition.

It’s great for things like showing text, setting styles, or deciding between two values.

When Not to Use It

Avoid the ternary when:

  • You’re dealing with multiple conditions.
  • It makes your code hard to read.
  • The action inside the condition is too long.
javascript
1