JavaScript Ternary Operator: Complete Syntax Guide

The ternary operator is a one-line if/else. Learn the syntax, when to use it for clean code, and the readability mistakes to avoid.

4 min read

The ternary operator is a one-line shortcut for an if/else that returns a value. It has three parts: a condition, a value when true, and a value when false.

javascriptjavascript
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
 
console.log(status); // "Adult"

This single line does the same thing as the four-line if/else version below, since both assign the same result to status depending on the same condition:

javascriptjavascript
let status;
if (age >= 18) {
  status = "Adult";
} else {
  status = "Minor";
}

The ternary is shorter because it is an expression: it produces a value directly, which means you can use it anywhere a value is expected.

Ternary Syntax

javascriptjavascript
condition ? valueIfTrue : valueIfFalse
  • condition: any expression that evaluates to true or false. This goes before the ?.
  • ?: separates the condition from the true value. Think "then."
  • valueIfTrue: the result when the condition is true.
  • :: separates the true value from the false value. Think "otherwise."
  • valueIfFalse: the result when the condition is false.

The entire ternary expression evaluates to a single value. That is the key difference from if/else: a ternary is an expression that produces a value, while if/else is a statement that runs code.

Practical Examples

Assigning a value based on a condition

The most common use of a ternary is picking between two values and storing the result in a variable, which is exactly the pattern shown earlier with age and status:

javascriptjavascript
const isLoggedIn = true;
const buttonText = isLoggedIn ? "Dashboard" : "Log In";
 
console.log(buttonText); // "Dashboard"

Inside template literals

Because a ternary is an expression, you can use it directly inside a template literal instead of computing a separate variable first:

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

This is much cleaner than computing the plural form separately. The ternary decides whether to add an "s" right where the string is built.

Inline with return statements

A ternary also works directly after return, which avoids declaring a variable just to hold the result before returning it:

javascriptjavascript
function getFee(isMember) {
  return isMember ? 5 : 20;
}
 
console.log(getFee(true));  // 5
console.log(getFee(false)); // 20

Setting CSS classes in UI frameworks

A similar pattern shows up constantly in frontend code, where a ternary decides which class name to append based on component state:

javascriptjavascript
const isActive = true;
const className = `nav-link ${isActive ? "active" : ""}`;
console.log(className); // "nav-link active"

Ternary vs if/else: When to Use Which

Ternaryif/else
const x = cond ? a : b;if (cond) { x = a; } else { x = b; }
Returns a valueRuns code blocks
Good for simple value picksGood for multi-step branches
One expression, one lineMultiple statements, multiple lines
Can be used inside other expressionsMust stand alone as a statement

Use a ternary when both branches produce a value and the logic is simple. Use if/else when each branch does more than one thing: calling functions, updating multiple variables, or running loops.

javascriptjavascript
// Ternary: clean for value assignment
const label = isEmpty ? "No data" : `${count} records`;

A multi-step branch like this one needs if/else instead, since each path calls more than one function and a ternary can only ever produce a single value:

javascriptjavascript
// if/else: better for multi-step branches
if (hasPermission) {
  fetchData();
  updateUI();
  logAccess();
} else {
  showAccessDenied();
  redirectToLogin();
}

Common Mistakes

Using a ternary when you only need an if

A ternary always requires both a ? and : branch. If you only need to act when a condition is true, use if or the AND short-circuit pattern:

javascriptjavascript
// Wrong: awkward no-op with null
isReady ? startApp() : null;
 
// Right: use if
if (isReady) startApp();
 
// Also right: use && for simple one-liners
isReady && startApp();

Nesting ternaries

You can nest ternaries by chaining another ternary inside the false branch, but they quickly become hard to read as more conditions stack up:

javascriptjavascript
// Hard to read
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
 
// Better as if/else if
let grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";

For more on nesting ternaries and how to do it safely, see the chaining ternary operators guide.

Where Ternaries Shine in Real Code

Ternaries are especially useful in React and similar frameworks where you need expressions, not statements, inside JSX:

javascriptjavascript
// Inside JSX: ternary works because it is an expression
<div>
  {isLoading ? <Spinner /> : <Content data={data} />}
</div>
 
// if/else does not work here because it is a statement, not an expression

Ternaries are also clean inside array methods like map, where the callback must return a value rather than run a block of statements:

javascriptjavascript
const scores = [85, 92, 60, 78];
const results = scores.map(s => s >= 70 ? "Pass" : "Fail");
 
console.log(results); // ["Pass", "Pass", "Fail", "Pass"]

The key rule: if the ternary makes your code shorter and the intent is obvious, use it. If you pause to parse the logic, rewrite it as if/else. For the full if/else pattern, see the if else statements guide.

Rune AI

Rune AI

Key Insights

  • The ternary operator has three parts: condition ? valueIfTrue : valueIfFalse.
  • It returns a value, which makes it ideal for variable assignments.
  • Always have both ? and : branches. A ternary cannot have only a true branch.
  • Use ternaries for simple value picks; use if/else for multi-step branches.
  • Do not nest ternaries more than one level deep.
  • A ternary is an expression, so it can be used inside template literals, JSX, and console.log.
RunePowered by Rune AI

Frequently Asked Questions

What does the ? and : mean in a ternary?

The ? separates the condition from the true-value. The : separates the true-value from the false-value. Read it as: condition ? valueIfTrue : valueIfFalse. Think of ? as 'then' and : as 'otherwise.'

Can I use a ternary without an else part?

No. The ternary operator always requires both a true and a false branch. If you only need to act when a condition is true and do nothing otherwise, use a regular if statement or the && short-circuit pattern.

Is the ternary operator the same as an if statement?

It can produce the same result for simple value assignments, but they are different: a ternary is an expression that returns a value, while an if/else is a statement that runs code blocks. Use a ternary when you need to assign a value; use if/else when each branch runs multiple statements.

Conclusion

The ternary operator (? :) is a one-line conditional that returns a value. It is perfect for simple if/else assignments where both branches produce a value. Use it when it makes your code shorter and clearer. Avoid it when the condition is complex, the branches do more than return a value, or when nesting ternaries makes the logic hard to follow.