DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is a Ternary Operator?

A ternary operator is a short way to write an if...else statement. It checks a condition and returns one of two values depending on whether the condition is true or false.

Syntax:

condition ? expressionIfTrue : expressionIfFalse;

? — if the condition is true
: — separates the true and false results

JavaScript:

let age = 20;

let result = age >= 18 ? "Eligible" : "Not Eligible";

console.log(result);

Output:

Eligible.

Difference between if...else and ternary:

let mark = 80;

if (mark >= 35) {
console.log("Pass");
} else {
console.log("Fail");
}

Using ternary operator:

let mark = 80;

console.log(mark >= 35 ? "Pass" : "Fail");

Output for both:

Pass.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ •

The name of the operator is actually the 'conditional' operator. It is sometimes called the ternary operator as a ternary operator is an operator that takes three operands, and JS only has one such operator. Similarly, unary operators take one operand, and binary operators take two.

Also, it is not a short way to write if..else - it is a short way to achieve the same effect as one particular usage of if..else - but if..else is a flow control construct NOT an operator. There any many things you can do with if..else that simply cannot be done with the conditional operator.