Course contentsShow
← JavaScript
Lesson 230 of 2,7236. Booleans and ConditionalsFree lesson

Nested Ternaries

Learn how to chain ternaries for multiple conditions, and why readability suffers.

Nested Ternaries

You'll learn how to chain ternary operators for multiple conditions—and why doing so can hurt readability.

You already know the basic ternary operator: condition ? valueIfTrue : valueIfFalse. But what if you have more than two outcomes? You can nest ternaries by placing another ternary inside the "false" branch (or even the "true" branch).

How It Works

Instead of just two branches, you can chain conditions:

let age = 25;
let category = age < 13 ? "child" : age < 20 ? "teen" : "adult";
// category is "adult"

This reads as: "If age is less than 13, return 'child'. Otherwise, if age is less than 20, return 'teen'. Otherwise, return 'adult'."

You're essentially putting a second ternary in the valueIfFalse position of the first ternary.

The Readability Problem

While nested ternaries are technically valid, they quickly become hard to read:

let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";

This works, but it's dense and harder to debug. Imagine adding more conditions—it becomes a horizontal maze. Most developers prefer if...else if...else chains for multiple conditions because they're clearer and easier to maintain.

When You Might Use Them

Stick to nesting ternaries when you have exactly two levels and the logic is simple. Beyond that, readability suffers.

Key Takeaway: Nested ternaries let you handle multiple conditions in one expression, but they sacrifice readability—use them sparingly, and prefer if...else chains for complex logic.