Lesson 16 +15 XP

The Ternary Operator

The Ternary Operator

The ternary operator is a short way to write an if...else decision.

The syntax

condition ? valueIfTrue : valueIfFalse

A simple example

let result = age >= 18 ? "Adult" : "Minor";

This is the same as:

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

Why use it?

The ternary is compact and perfect for assigning a value based on a condition. It reads like a question: "is age 18 or more? then Adult, else Minor".

When not to use it

For complex logic with many branches, a regular if...else is clearer. Do not nest ternaries too deeply, it gets hard to read.

Multiple conditions

let status = score >= 90 ? "A" : score >= 80 ? "B" : "C";

TL;DR

  • Syntax: condition ? a : b.
  • Returns a if true, b if false.
  • A compact replacement for simple if...else.
  • Use regular if...else for complex logic.