01 / 21
? :

The Ternary
Operator

Master JavaScript's most concise conditional expression: write cleaner code with the ? : operator.

JavaScript

What is a Conditional?

Every program makes decisions. A conditional checks whether something is true or false, then runs different code depending on the result.

condition? true run code A false run code B

The if/else You Already Know

An if/else statement works, but it takes up multiple lines even for a simple assignment:

let message;

if (score >= 60) {
  message = "Pass";
} else {
  message = "Fail";
}

Enter the Ternary Operator

The ternary operator is JavaScript's only operator that takes three operands. It compresses an if/else into a single expression:

let message = score >= 60 ? "Pass" : "Fail";

Anatomy of ? :

condition ? valueIfTrue : valueIfFalse Evaluates to true or false Returned when truthy Returned when falsy

The Formal Syntax

condition ? expressionIfTrue : expressionIfFalse
condition
Any expression that JavaScript evaluates as truthy or falsy.
expressionIfTrue
Evaluated and returned when the condition is truthy.
expressionIfFalse
Evaluated and returned when the condition is falsy.

Expression vs Statement

Ternary (Expression) if/else (Statement)
Returns a value? Yes No
Can assign directly Yes No
Embed in template literal Yes No
Multi-line logic Avoid Preferred
Readability (complex) Lower Higher

How to Apply It

1
Identify the condition: What boolean question are you asking?
2
Determine two outcomes: What value for true? What value for false?
3
Write the expression: condition ? trueValue : falseValue
4
Assign or use the result: Store it in a variable, return it, or embed it.
5
Readability check: If the line exceeds ~80 characters, consider if/else instead.

Example 1: Basic Assignment

Assign a greeting based on the time of day:

const hour = 14;

const greeting = hour < 12 ? "Good morning" : "Good afternoon";

console.log(greeting); // "Good afternoon"
\(14 < 12\)
false "Good afternoon" condition is falsy, so the value after : is returned

Example 2: Template Literals

Embed a ternary directly inside a template literal:

const items = 3;

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

Example 3: Function Returns

Use a ternary as the return value of a function:

function getDiscount(isMember) {
  return isMember ? 0.20 : 0.05;
}

console.log(getDiscount(true)); // 0.20
console.log(getDiscount(false)); // 0.05

Chained Ternaries

You can chain ternaries to handle multiple conditions, like an if/else if/else:

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

Truthy vs Falsy Values

The condition in a ternary does not have to be a strict boolean. JavaScript coerces it. Here are the falsy values:

Falsy Values
false, 0, "", null, undefined, NaN
Everything Else
All other values are truthy: non-zero numbers, non-empty strings, objects, arrays.
const name = "";
const display = name ? name : "Anonymous";
// "" is falsy, so display = "Anonymous"

Where to Use Ternaries

✓ Variable assignment
const x = a ? b : c;
✓ Return values
return a ? b : c;
✓ Template literals
`${a ? b : c}`
✓ Default arguments
fn(a ? b : c)

Common Mistakes

✕ Side effects in branches
Avoid x > 0 ? doA() : doB() for side-effect-only calls. Use if/else for actions, ternary for values.
✕ Deeply nested ternaries
More than one level of chaining hurts readability. Refactor into if/else or a helper function.
✕ Forgetting the colon
Every ? must have a matching :. Omitting it causes a SyntaxError.

Quick Reference Cheat Sheet

Pattern Code When to Use
Simple assignment a ? b : c One variable, two options
Inline in template `${a ? b : c}` Dynamic strings
Function return return a ? b : c; Short function bodies
Chained a ? x : b ? y : z 2-3 uniform conditions max
Avoid a ? fn() : fn() Side effects: use if/else

Question 1 of 5

What does the following expression evaluate to?

\(5 > 3\) ? "yes" : "no"

Question 2 of 5

Which of the following is a valid use of the ternary operator?

Question 3 of 5

What is the value of result?

const result = 0 ? "truthy" : "falsy";

Question 4 of 5

Why can you use a ternary inside a template literal but not an if/else?

Question 5 of 5

What does this chained ternary return when \(x = 75\)?

\(x \ge 90\) ? "A" : \(x \ge 80\) ? "B" : \(x \ge 70\) ? "C" : "F"