Tutorials JavaScript Ternary Operator
Ch 18 / 78
Chapter 18 Beginner 5 min read JavaScript

Ternary Operator ( ? : )

The ternary operator is JavaScript's only three-operand operator — a concise, one-line shorthand for a simple if / else. Written as condition ? valueIfTrue : valueIfFalse, it's the go-to tool for simple value assignments, inline expressions, and JSX rendering. Mastering it helps you write shorter, more expressive code — while knowing when not to use it keeps your code readable.

What you'll learn
Ternary syntax — condition, ?, :, and their roles
Ternary vs if/else — when each is appropriate
Ternary for default values and null checks
Chained ternaries — how and when to use them
Ternary in template literals and JSX (React)
Common pitfalls and when to avoid ternary

Ternary Operator Overview

The ternary operator takes three operands: a condition, an expression to evaluate when the condition is truthy, and an expression when it's falsy. It always evaluates to a value — making it perfect for assignments and inline expressions.

condition
Any expression that evaluates to truthy or falsy. Written before the ?.
? truthy value
Expression returned or executed when condition is truthy.
: falsy value
Expression returned or executed when condition is falsy.
Chaining
Ternaries can be nested to handle multiple branches — use sparingly.
JSX / React
Ternary is the standard for conditional rendering inside JSX.
Part Role Example
condition Evaluated for truthiness age >= 18
? Separator — "then" condition ? ...
valueIfTrue Returned when condition is truthy ? "adult"
: Separator — "else" ... : ...
valueIfFalse Returned when condition is falsy : "minor"

Syntax & Anatomy

The ternary operator is the only JavaScript operator that takes three operands. Its entire purpose is to pick between two values based on a condition — all on a single line.

Anatomy of the ternary operator
condition Any expression that resolves to truthy or falsy. Can include comparisons, logical operators, function calls, or any value.
? The "then" separator. Marks the start of the expression to evaluate when condition is truthy.
valueIfTrue Expression evaluated and returned when condition is truthy. Can be a value, function call, or nested ternary.
: The "else" separator. Marks the start of the expression to evaluate when condition is falsy.
valueIfFalse Expression evaluated and returned when condition is falsy. Required — unlike else in if statements.
JavaScript — Ternary Syntax
// ── Full syntax ──────────────────────────────────────────────
// condition ? valueIfTrue : valueIfFalse

const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

// ── Equivalent if / else ──────────────────────────────────────
let result;
if (age >= 18) {
result = "adult";
} else {
result = "minor";
}
// Both produce the same output — ternary is shorter

// ── Multi-line format (for readability) ──────────────────────
const label = score >= 60
? "Pass ✓"
: "Fail ✗";
// Breaking across lines keeps long ternaries readable
✗ Verbose — if / else
let label;
if (score >= 60) {
  label = "Pass";
} else {
  label = "Fail";
}
// 5 lines for one assignment
✓ Concise — Ternary
const label =
  score >= 60
    ? "Pass"
    : "Fail";
// 4 lines, cleaner intent
Best Practice
When a ternary would span more than one line, format it vertically: put ? and : at the start of new lines. This preserves the clarity benefit of ternary without cramming logic onto one hard-to-read line.

How Truthiness Works in the Ternary

The ternary operator evaluates the condition for its truthiness — not strictly for true. Any value can be a condition. The same 6 falsy values that affect if statements apply here.

condition ? A : B
Returns A when truthy
true ? A : B → A
1 ? A : B → A
"hello" ? A : B → A
[] ? A : B → A (truthy!)
{} ? A : B → A (truthy!)
condition ? A : B
Returns B when falsy
false ? A : B → B
0 ? A : B → B
"" ? A : B → B
null ? A : B → B
undefined ? A : B → B
JavaScript — Truthy & Falsy in Ternary
// ── Truthy conditions → first branch ─────────────────────────
const a = true ? "yes" : "no"; // "yes"
const b = 1 ? "yes" : "no"; // "yes"
const c = "hi" ? "yes" : "no"; // "yes"
const d = [] ? "yes" : "no"; // "yes" — empty array is truthy!
const e = {} ? "yes" : "no"; // "yes" — empty object is truthy!

// ── Falsy conditions → second branch ─────────────────────────
const f = false ? "yes" : "no"; // "no"
const g = 0 ? "yes" : "no"; // "no"
const h = "" ? "yes" : "no"; // "no"
const i = null ? "yes" : "no"; // "no"
const j = undefined ? "yes" : "no"; // "no"

// ── Common gotcha — checking array length ─────────────────────
const items = [];
const msg = items ? "has items" : "empty"; // "has items" — [] is truthy!
const msg2 = items.length ? "has items" : "empty"; // "empty" — ✓ correct check

Common Use Cases

The ternary operator shines in specific situations. These are the patterns you'll encounter most often in real JavaScript and React codebases.

assignment
Conditional Value
Assign one of two values to a variable based on a condition.
const x = a > b ? a : b;
default
Fallback / Default
Use a fallback when a value might be null or undefined.
name ? name : "Guest"
template
Inside Strings
Embed conditional logic directly inside template literals.
`${n} item${n !== 1 ? "s" : ""}`
JSX
React Rendering
Conditionally render components in JSX — the only clean inline option.
isOn ? <On /> : <Off />
return
Function Return
Return one of two values from a function in a single expression.
return x > 0 ? x : -x;
class
CSS Class Toggle
Dynamically apply one CSS class or another based on state.
active ? "btn-on" : "btn-off"
JavaScript — Ternary Use Cases
// ── 1. Conditional value assignment ──────────────────────────
const age = 17;
const ticket = age >= 18 ? "Full price" : "Concession";
// "Concession"

// ── 2. Null / undefined fallback ─────────────────────────────
const username = null;
const display = username ? username : "Guest";
// "Guest" (also consider: username ?? "Guest")

// ── 3. Template literals ─────────────────────────────────────
const items = 3;
console.log(`You have ${items} item${items !== 1 ? "s" : ""} in your cart`);
// "You have 3 items in your cart"

// ── 4. Inline return from arrow function ─────────────────────
const abs = n => n >= 0 ? n : -n;
console.log(abs(-7)); // 7
console.log(abs(5)); // 5

// ── 5. CSS class toggling ─────────────────────────────────────
const isActive = true;
const btnClass = isActive ? "btn btn-active" : "btn btn-idle";

// ── 6. JSX / React conditional rendering ─────────────────────
// const panel = isLoggedIn ? <Dashboard /> : <Login />;
// const badge = unread > 0 ? <Badge count={unread} /> : null;

Chained Ternaries

You can nest ternaries to handle more than two branches by placing another ternary after the :. This is called a chained ternary. Use it for simple grading or mapping logic — but cap it at 2–3 levels before switching to if/else or a lookup object.

✗ Unreadable — deep chain
// Hard to parse at a glance
const g = s>=90?"A":s>=80?"B":s>=70?"C":s>=60?"D":"F";
✓ Readable — formatted chain
const grade =
  score >= 90 ? "A"
  : score >= 80 ? "B"
  : score >= 70 ? "C"
  : score >= 60 ? "D"
  : "F";
JavaScript — Chained Ternary
// ── Grade calculator — chained ternary ───────────────────────
const score = 74;

const grade =
score >= 90 ? "A — Excellent 🏆"
: score >= 80 ? "B — Good 👍"
: score >= 70 ? "C — Satisfactory ✔"
: score >= 60 ? "D — Passing ⚠"
: "F — Fail ✗";

console.log(grade); // "C — Satisfactory ✔"

// ── Traffic light — simple chain (2 levels max) ──────────────
const light = "yellow";
const action =
light === "green" ? "Go 🟢"
: light === "yellow" ? "Slow down 🟡"
: "Stop 🔴";

console.log(action); // "Slow down 🟡"

// ── Beyond 3 levels? Use if/else or a lookup object ───────────
const grades = { A: 90, B: 80, C: 70, D: 60 };
const letter = Object.keys(grades).find(k => score >= grades[k]) || "F";
// Cleaner for 5+ branches ↑
Readability Warning
Stop chaining when you reach 3 levels or when each branch has side effects. At that point, an if/else if/else chain or a lookup object is always more readable, easier to test, and simpler to modify. The goal is clarity — not conciseness at all costs.

Ternary vs ?? Nullish Coalescing

A common use of ternary is providing a default value when something is null or undefined. Since ES2020, the nullish coalescing operator (??) does this more precisely — it only falls back on null or undefined, not all falsy values.

Expression Falls back when… Keeps 0 / "" / false?
x ? x : "default" x is any falsy value No
x ?? "default" x is null or undefined only Yes
x || "default" x is any falsy value No
JavaScript — Ternary vs ?? vs ||
// ── Ternary for default (checks all falsy values) ────────────
const count = 0;
const a = count ? count : 10; // 10 ⚠ — 0 is falsy, so 10 is returned

// ── ?? nullish — only falls back on null / undefined ─────────
const b = count ?? 10; // 0 ✓ — 0 is NOT null/undefined, kept
const c = null ?? "default"; // "default" ✓
const d = undefined ?? "default"; // "default" ✓

// ── || logical OR — also checks all falsy ────────────────────
const e = count || 10; // 10 ⚠ — same issue as ternary
const f = "" || "hi"; // "hi" ⚠ — empty string is falsy

// ── Rule of thumb ─────────────────────────────────────────────
// Use ?? when you ONLY want to replace null / undefined
// Use ternary when your fallback logic depends on truthiness
Modern Best Practice
Prefer ?? over x ? x : "default" when you're guarding against null or undefined. It's more precise and won't accidentally override valid falsy values like 0, "", or false that you may actually want to keep.

Ternary in Template Literals & JSX

Two of the most practical places you'll use the ternary operator are inside template literals (for dynamic strings) and in JSX (for conditional React rendering). In both cases, you need an expression rather than a statement — and ternary delivers.

JavaScript — Ternary in Template Literals & JSX
// ── Template literals — pluralisation ────────────────────────
const count = 1;
console.log(`${count} message${count !== 1 ? "s" : ""}`); // "1 message"

const count2 = 5;
console.log(`${count2} message${count2 !== 1 ? "s" : ""}`); // "5 messages"

// ── Greeting with time of day ─────────────────────────────────
const hour = 14;
const greeting = `Good ${hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening"}!`;
console.log(greeting); // "Good afternoon!"

// ── Dynamic CSS classes ───────────────────────────────────────
const isError = true;
const className = `alert ${isError ? "alert-danger" : "alert-success"}`;
// "alert alert-danger"

// ── JSX — React conditional rendering ────────────────────────
// function Navbar({ isLoggedIn }) {
// return (
// <nav>
// {isLoggedIn ? <UserMenu /> : <LoginButton />}
// {unread > 0 ? <Badge count={unread} /> : null}
// </nav>
// );
// }

When NOT to Use the Ternary

Ternary is great for conciseness — but it can hurt readability when overused. There are clear cases where if/else is the better choice.

Situation Use Ternary? Why
Simple value assignment ✓ Yes Clean and readable
JSX conditional rendering ✓ Yes Only expression-based option in JSX
Template literal inline ✓ Yes Can't use if statement inside ${ }
Side effects (console.log, mutations) ✗ No Use if/else — ternary should produce a value
4+ nested ternaries ✗ No Use if/else chain or lookup object instead
Complex conditions on each branch ⚠ Caution Multi-line blocks belong in if/else
JavaScript — Ternary Pitfalls to Avoid
// ── ✗ BAD — side effects in ternary ──────────────────────────
isLoggedIn ? console.log("Welcome") : console.log("Please log in");
// Use if/else instead — ternary is for values, not statements

// ── ✓ GOOD — if/else for side effects ────────────────────────
if (isLoggedIn) {
console.log("Welcome");
} else {
console.log("Please log in");
}

// ── ✗ BAD — unreadable deep nest ─────────────────────────────
const x = a ? b ? "ab" : "a" : b ? "b" : "none";
// ↑ Very hard to parse. Use if/else or a lookup table

// ── ✗ BAD — multi-statement branch ───────────────────────────
// isAdmin ? (setRole("admin"), loadPanel()) : redirect("/login");
// ↑ Use if/else when each branch does more than return a value

// ── ✓ GOOD — clean single-value ternaries ────────────────────
const icon = isError ? "⚠" : "✓";
const color = score >= 60 ? "green" : "red";
const label = isAdmin ? "Admin" : "User";

Try It — Live Editor

Experiment with the JavaScript ternary operator below. Change values, test different conditions, and see how chaining works — all without leaving this page.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These ternary patterns appear constantly in modern JavaScript and React projects. Each is a clean, expressive one-liner that replaces verbose if/else logic.

JavaScript — Ternary Recipes
// ── Clamp a value between min and max ────────────────────────
const clamp = (val, min, max) => val < min ? min : val > max ? max : val;
console.log(clamp(-5, 0, 100)); // 0
console.log(clamp(42, 0, 100)); // 42
console.log(clamp(150, 0, 100)); // 100

// ── Toggle boolean ────────────────────────────────────────────
let isOpen = false;
isOpen = isOpen ? false : true; // or: isOpen = !isOpen;

// ── Absolute value ───────────────────────────────────────────
const abs = n => n >= 0 ? n : -n;

// ── Max of two numbers ────────────────────────────────────────
const max = (a, b) => a > b ? a : b;

// ── Pluralise a word ──────────────────────────────────────────
const plural = (n, word) => `${n} ${word}${n !== 1 ? "s" : ""}`;
console.log(plural(1, "file")); // "1 file"
console.log(plural(3, "file")); // "3 files"

// ── Conditional object property (ES2018) ─────────────────────
const isAdmin = true;
const user = {
name: "Alice",
...(isAdmin ? { role: "admin", access: "full" } : { role: "viewer" })
};
// { name: "Alice", role: "admin", access: "full" }

// ── Loading / error / data pattern (React) ───────────────────
// const content = isLoading ? <Spinner /> : isError ? <Error /> : <DataView data={data} />;
⚡
Free Resource
Download our JavaScript Cheat Sheet
All conditionals, control flow patterns & operator quick reference — one printable page.
Get Sheet
Quick Check
What does null ? "yes" : "no" evaluate to?
Quick Check
What does 0 ?? "default" return?
Quick Check
Which case is ternary not recommended for?
Chapter Summary
  • The ternary operator (condition ? a : b) is JavaScript's only three-operand operator — a concise shorthand for a simple if/else that always evaluates to a value.
  • The condition is evaluated for truthiness, not strict true. The same 6 falsy values apply: false, 0, "", null, undefined, NaN.
  • Use ternary for simple value assignments, template literals, inline arrow functions, and JSX rendering — places where you need an expression rather than a statement.
  • Chained ternaries handle multiple branches but hurt readability beyond 2–3 levels. Format them vertically with ? and : at the start of new lines for clarity.
  • For null/undefined defaults, prefer the nullish coalescing operator (??) — it only falls back on null and undefined, preserving valid falsy values like 0 and "".
  • Avoid ternary for side effects, multi-statement branches, or deeply nested logic. Those belong in if/else blocks for readability and maintainability.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel