Ternary Operator

The ternary operator is a concise way to write conditional expressions in JavaScript. It is often used as a shorthand for if...else statements when you want to assign values or return results based on a condition.

Illustration of ternary_operator
Illustration of ternary_operator

💡 Syntax Overview

condition ? expressionIfTrue : expressionIfFalse

Here’s how it works:

  • condition is evaluated first.
  • If condition is true, expressionIfTrue runs and its value is returned.
  • If condition is false, expressionIfFalse runs and its value is returned.
Ternary Operator vs if...else
if...elseternary operator
let result;
if (age >= 18) {
  result = 'Adult';
} else {
  result = 'Minor';
}
let result = age >= 18 ? 'Adult' : 'Minor';

💡 When to Use

Use the ternary operator for simple, concise conditionals that return values. Avoid using it for complex or multi-line logic to keep code readable.

📌 Deep Dive: Basic Example

JAVASCRIPT
const score = 75;
const grade = score >= 60 ? 'Pass' : 'Fail';
console.log(grade);
Output
Pass

The ternary operator can also be nested, but be cautious as this can reduce readability:

📌 Deep Dive: Nested Ternary

JAVASCRIPT
const num = 0;
const sign = num > 0 ? 'Positive' : num < 0 ? 'Negative' : 'Zero';
console.log(sign);
Output
Zero

⚠️ Avoid Overusing Nested Ternaries

Nested ternary operators can be hard to read and debug. Prefer if...else for complex conditions.

The ternary operator can also be used directly in expressions or JSX (in frameworks like React) to conditionally render values or elements.

💡 Summary

  • The ternary operator is a compact alternative to if...else for conditional expressions.
  • Syntax: condition ? exprIfTrue : exprIfFalse.
  • Best for simple conditionals returning values.
  • Use cautiously with nested ternaries to maintain readability.