The Ternary Operator

JavaScript ES2024 · ✓ verified by execution on

The conditional (ternary) operator is the only JavaScript operator that takes three distinct operands: a condition followed by a question mark (?), then an expression to execute if the condition evaluates to truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

This operator is frequently used as a concise alternative to a standard if...else statement, particularly when you want to assign a value based on a condition directly.

javascript
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
console.log(status);
Output
Adult

Because it evaluates truthiness directly, you can pass it any value and it will coerce it using the standard truthy and falsy rules. Falsy values include null, NaN, 0, the empty string (""), and undefined.

javascript
const name = '';
const greeting = name ? `Hello, ${name}!` : 'Hello, stranger!';
console.log(greeting);
Output
Hello, stranger!

Expressions vs Statements

A ternary looks like a compact if, and for simple cases it reads like one. They are not interchangeable, because they belong to different categories of the language.

A ternary is an expression: it evaluates to a value, so it can go anywhere a value can — the right-hand side of an assignment, inside a template literal, or as an argument to a function. if...else is a statement: it performs an action and produces nothing, which is why const x = if (a) {...} is not valid JavaScript. That gap is the ternary’s whole purpose.

Both branches must therefore be expressions too. Put a statement in one — a return, a break — and you get a SyntaxError.

const result = condition ? 'Yes' : 'No'; Condition Truthy Falsy Evaluates to a SINGLE VALUE Assigned directly to "result"
Ternary expressions evaluate to values, unlike if statements

You can clearly see this flexibility when utilizing ternaries directly inside function calls:

javascript
const count = 1;
console.log(count === 1 ? 'item' : 'items');
Output
item

Short-Circuiting and Side Effects

Ternary operators intelligently short-circuit, which means if the condition evaluates to truthy, the falsy branch is entirely ignored and never executed! This is critically important if your branches contain function calls with observable side effects.

Can you predict the final value of the counter?

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

let count = 0;
function increment() {
  count += 10;
  return 'called';
}

const status = true ? 'ignored' : increment();
console.log(count);
Output
0

Nesting Ternaries

The conditional operator is right-associative, which formally means it can be chained indefinitely. Nesting multiple ternary operators is perfectly valid syntax, but can rapidly make your code completely unreadable.

javascript
const score = 85;
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
console.log(grade);
Output
B

In cases of deep complexity, a standard if/else or switch statement is universally preferred over an aggressively nested ternary!

Check yourself

You can omit the else branch (the part after the colon) in a ternary operator.

Reveal answer

False, both branches are strictly required. A missing branch causes a syntax error. — Both branches are required. A ternary must always have three parts: condition, truthy expression, falsy expression. A missing branch causes a syntax error.

If the condition is truthy, the falsy expression is still evaluated.

Reveal answer

False, ternary operators short-circuit. If the condition is truthy, the falsy expression is never evaluated. — Ternary operators short-circuit. If the condition is truthy, the falsy expression is never evaluated (which is important if it contains a function call with side effects).

A ternary operator is just syntactic sugar that is converted into an if-statement at runtime.

Reveal answer

False, a ternary is an expression evaluated to a value, fundamentally different from a statement at the AST level. — While similar in logic, a ternary is an expression evaluated to a value, fundamentally different from a statement at the AST level.

Challenges

Challenge 1 +20 XP

Use a ternary operator to assign 'Yes' to isEven if num is even, and 'No' if it is odd.

javascript
  • Test 1 — expects "Yes"
Need a hint? (−25% XP)

The structure is: condition ? truthy_value : falsy_value.

Show solution (0 XP)
const num = 4;
const isEven = num % 2 === 0 ? 'Yes' : 'No';
console.log(isEven);

Challenge 2 +20 XP

Use a ternary operator to check if a user is logged in. Log 'Welcome back!' if true, and 'Please log in.' if false.

javascript
  • Test 1 — expects "Please log in."
Need a hint? (−25% XP)

Use console.log() and put the ternary expression directly inside.

Show solution (0 XP)
const isLoggedIn = false;
console.log(isLoggedIn ? 'Welcome back!' : 'Please log in.');