Operators

Ternary Operator in JavaScript: Simplifying Conditional Logic

What is the Ternary Operator?

The ternary operator ?: is a shorthand for a simple if...else statement, evaluating a condition and returning one of two values.

Syntax

condition ? valueIfTrue : valueIfFalse;

Example

let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // "Adult"

When to Use It

Ternary operators are best for short, simple conditions. For multiple conditions or complex logic, if...else or switch statements are more readable.

Ready to master real-world JavaScript development?

Learn JavaScript hands-on with mentor-led, live sessions.

Explore Course