Ternary Operator (Conditional Operator)

This operator is a short and compact way to write if-else logic in a single line.

Ternary Operator

Syntax:

condition ? valueIfTrue : valueIfFalse;

It evaluates the condition:

  • If true → returns the first value
  • If false → returns the second value
let age = 17;
let result = age >= 18 ? "Adult" : "Minor";
console.log(result); // Minor

It directly assigns the result based on the condition, so it is commonly used for variable assignment.

let marks = 80;
let grade = marks >= 50 ? "Pass" : "Fail";
console.log(grade); // Pass

It can also be used inside expressions:

console.log(10 > 5 ? "Yes" : "No"); // Yes

You can chain multiple conditions, but readability becomes poor:

let marks = 85;

let grade = marks >= 90 ? "A" :
            marks >= 75 ? "B" :
            marks >= 50 ? "C" : "Fail";
console.log(grade); // B

This works, but it is harder to read and debug.

It returns values, unlike if-else which executes blocks:

let x = true ? 10 : 20;
console.log(x); // 10

It is often used in UI rendering and quick decisions:

let isLoggedIn = true;
let message = isLoggedIn ? "Welcome Back" : "Please Login";

📣 Follow us for more updates:

Follow on LinkedIn Join WhatsApp Channel
Scroll to Top