H.dev

Ternary Operator

The Shorthand If/Else

As you write more JavaScript, you will often find yourself writing very simple if/else statements that only assign a value to a variable based on a condition.

// Traditional approach
let age = 20;
let status;

if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}

This works perfectly, but it takes up 7 lines of code.

Enter the Ternary Operator

The ternary operator is the only JavaScript operator that takes three operands. It is used as a one-line shorthand for an if/else statement.

Syntax: condition ? expressionIfTrue : expressionIfFalse;

Let's rewrite the above code using the ternary operator:

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";

Why Use It?

The ternary operator makes your code incredibly clean and concise. You will see it used constantly in modern frontend frameworks like React for conditionally rendering components or toggling classes! However, don't overuse it for complex nested conditions, as it can quickly become hard to read.

💡 Himanshu's Tip:

Ternary operators are fantastic for rendering UI components conditionally in React, but don't nest them! If you find yourself writing a ternary inside a ternary, stop and rewrite it as a standard if/else. Readability always beats writing less lines.

Interview Questions

  1. How many operands does a ternary operator take?
  2. What is the syntax structure of a ternary operator?
  3. In what scenarios is a ternary operator preferred over a standard if-else statement?

Design & Developed by Himanshu Dubey © 2026