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.
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.
?.| 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.
// ── 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 readableif (score >= 60) {
label = "Pass";
} else {
label = "Fail";
}
// 5 lines for one assignment
score >= 60
? "Pass"
: "Fail";
// 4 lines, cleaner intent
? 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.
// ── 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.
// ── 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.
const g = s>=90?"A":s>=80?"B":s>=70?"C":s>=60?"D":"F";
score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: score >= 60 ? "D"
: "F";
// ── 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 ↑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 |
// ── 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?? 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.
// ── 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 |
// ── ✗ 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.
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.
// ── 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} />;
null ? "yes" : "no" evaluate to?0 ?? "default" return?- The ternary operator (
condition ? a : b) is JavaScript's only three-operand operator — a concise shorthand for a simpleif/elsethat 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 onnullandundefined, preserving valid falsy values like0and"". - Avoid ternary for side effects, multi-statement branches, or
deeply nested logic. Those belong in
if/elseblocks for readability and maintainability.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.