Making decisions · Lesson 13 of 77 · concept

The conditional operator

About 45 minutes.

By the end of this lesson you can

  • Write a conditional expression that produces one of two values.
  • Explain the difference between a statement that does something and an expression that is something.
  • Use a conditional in the middle of a value, where an if statement cannot go.
  • Recognise when a nested conditional should have stayed an if / else chain.

Statements do something. Expressions are something.

A mental model

This distinction has been quietly present since your first program, and this lesson is where it starts to pay. An expression is a piece of code that HAS a value: 2 + 2, price * 3, age >= 18, "hello". Wherever a value is expected, an expression can go. A statement is a piece of code that DOES something: an if, a variable declaration, a return. Statements are instructions; they have no value of their own.

That is why 'const total = if (member) { 8 } else { 14 };' is not merely unusual, it is impossible. The right-hand side of a const needs a value, and an if is not one. The if statement is perfectly capable of assigning to a variable - but the variable has to exist first, declared with let and no value, and then written to inside both branches. Three or four lines to make one decision.

The conditional operator is the expression version of that decision. Same question, same two outcomes, but it produces a value, so it can sit anywhere a value can sit.

condition ? this : that

Explanation

You write the condition, a question mark, the value to use when the condition is true, a colon, and the value to use when it is false. 'age < 18 ? 8 : 14' is an expression whose value is 8 or 14, decided when the line runs.

It is the only operator in JavaScript that takes three operands, which is why you will hear it called the ternary operator - 'ternary' just means three-part. Both names refer to this one operator, so they are interchangeable when you read about it.

Read the punctuation as words and it stops being cryptic: the question mark is 'then' and the colon is 'otherwise'. If age is under eighteen, then 8, otherwise 14.

MDN — Conditional (ternary) operator

Check there: The conditional operator takes three operands, evaluates the first as a condition, and produces the second operand when it is truthy and the third otherwise; it is the only JavaScript operator taking three operands.

The two places you will actually reach for it

Why it matters

The first is initialising a const. Deciding a value up front and then never changing it is exactly what const is for, and an if statement forces you to give that up: you must switch to let and leave the variable temporarily empty, which is a weaker promise to every future reader. A conditional keeps the const.

The second is in the middle of a value you are building - most often a piece of text. 'You have " + count + " message" + (count === 1 ? "" : "s")' picks the plural inside the expression that is assembling the sentence. An if statement cannot go in the middle of a string being joined together; there is nowhere to put it.

Notice the brackets around the conditional in that example. They are not decoration. + binds more tightly than ? :, so without them JavaScript reads the whole joined string as the condition - and a non-empty string is truthy, so it always takes the first branch. When a conditional appears inside a larger expression, wrap it.

Both branches should produce the same kind of thing

Explanation

Nothing stops you writing 'ok ? 42 : "no"', and JavaScript will not object. But whatever receives that value now has to cope with either a number or a piece of text, and every later line that uses it inherits that uncertainty. A conditional is at its best when the two branches are two versions of the same answer: two prices, two labels, two counts.

The related discipline is to keep the branches small. If either side needs a calculation of its own, the line stops being readable at a glance, which was the only reason to prefer it over an if. Compute first, then choose.

Two ways this goes wrong

A common mistake

The first is nesting. 'a ? 1 : b ? 2 : c ? 3 : 4' is legal, and it does read as a ladder once you know that the operator groups from the right - each colon's 'otherwise' half is the next whole question. Used carefully, with one short condition and one short value per line, it is a recognised idiom for a small lookup. Used carelessly, with conditions that need brackets and branches that need thought, it is the least readable line in the file. The test: if you cannot see all the branches at once without scrolling, or you want to add a comment to one of them, it should be an if / else chain.

The second is using it for its effects rather than its value. 'isAdmin ? showPanel() : hidePanel();' throws the value away and uses the operator purely to choose which function to call. It works, and it tells the reader the wrong story - it says 'here is a value being computed' when nothing is being computed. An if statement says 'here are two courses of action', which is what is actually happening. Use the operator when you want a value; use if when you want an action.

Recap

Recap

'condition ? whenTrue : whenFalse' is an expression, so it has a value and can appear anywhere a value can - including a const initialiser and the middle of a piece of text, both of which are closed to an if statement. Wrap it in brackets inside a larger expression, because + binds more tightly. Keep both branches the same kind of thing and keep them short. Prefer an if statement when you are choosing between actions rather than between values.

Worked examples

Every output below was produced by actually running the code in the same sandbox your exercises run in — it is not a prediction.

The same decision, twice

Both halves compute exactly the same thing. The difference is that one keeps a const and takes a line, and the other needs a let and takes five.

1const age = 15;2 3const price = age < 18 ? 8 : 14;4console.log(price);5 6let status;7if (age < 18) {8  status = "child";9} else {10  status = "adult";11}12console.log(status);
  • line 3

    The conditional produces a value, so it can be the right-hand side of a const. price can never change after this line, and a reader can see that from the keyword alone.

  • line 6

    The if version cannot start with const, because the variable must exist before either branch can assign to it. It is declared here with no value at all.

  • line 11

    Five lines and a mutable variable to make one decision. Neither version is wrong - but for a straight choice between two values, the first says more with less.

What it prints

8child

Choosing a word in the middle of a sentence

There is nowhere to put an if statement inside a string being joined together. This is the case the conditional operator exists for.

1function summary(count) {2  return "You have " + count + " message" + (count === 1 ? "" : "s") + ".";3}4 5console.log(summary(1));6console.log(summary(3));7console.log(summary(0));
  • line 2

    The brackets are required. Without them, + is applied first, so the condition would be the whole joined-up text so far - which is non-empty and therefore always truthy.

  • line 7

    0 takes the same branch as 3, which is correct English: you have 0 messages, not 0 message. The condition asks about 1 specifically rather than relying on truthiness.

What it prints

You have 1 message.You have 3 messages.You have 0 messages.

A chain, and the line where it stops paying

Four outcomes in one line. Compare it with the else-if ladder from lesson one: identical behaviour, a quarter of the space, and noticeably more to hold in your head.

1function band(score) {2  return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";3}4 5console.log(band(95), band(85), band(75), band(10));
  • line 2

    Groups from the right: everything after the first colon is itself one whole conditional, and so on. So it is tested left to right exactly like an else-if ladder, and the first true condition wins.

  • line 5

    Four calls, one line of output - console.log joins its arguments with a space. Each result comes from a different branch of the chain.

What it prints

A B C F

Check yourself

Not scored, not stored. Getting one wrong is the useful part.

These two lines differ by one pair of brackets. Predict both outputs - the second one is the mistake this check exists to burn in.

const isMember = true;console.log("Price: " + (isMember ? 8 : 14));console.log("Price: " + isMember ? 8 : 14);

What can a conditional expression do that an if statement cannot?

You are writing a chain of conditionals and one branch now needs two calculations and a short comment explaining a rule. What should you do?

Write it yourself

Exercise · core · 6 tests

Say it in plain English

Write itemsLabel(count) that turns a number into a phrase: 0 becomes 'no items', 1 becomes '1 item', and any other number becomes that number followed by ' items' - so 2 becomes '2 items'. Use the conditional operator to pick between the singular and the plural word, and handle the zero case however reads best to you. The starter code always uses the plural, so it is wrong for both 0 and 1.

What your code must do

itemsLabel returns the text 'no items' for 0, '1 item' for 1, and the number followed by a space and 'items' for every other number. It always returns text and never prints anything.

Define itemsLabel at the top level of your code — the tests call it by name.

Runs on your device in a sandbox with no network and no access to this page.

Worth remembering

  • What are the three parts of the conditional operator, and what does it produce?

    condition ? whenTrue : whenFalse. It is an expression, so it produces a value - unlike an if statement, which produces nothing.

  • Why does '"Price: " + isMember ? 8 : 14' not do what it looks like?

    + binds more tightly than ? :, so the condition becomes the whole joined text, which is truthy. Wrap the conditional in brackets.

  • When should a conditional expression be an if statement instead?

    When you are choosing between actions rather than values, or when a branch needs more than one short expression or a comment of its own.

Check this lesson against the source

We wrote the explanation; we did not invent the facts. This is the page that backs them.

MDN — Conditional (ternary) operator

Check there: The syntax condition ? exprIfTrue : exprIfFalse, its status as the only three-operand operator, and that it is an expression producing a value.

MDN — Expressions and operators

Check there: An expression is any valid unit of code that resolves to a value.

Prefer to read the source in a structured breakdown? Turn this doc into a breakdown

0 of 1 exercise in this lesson solved on this device

Consent version 2026-07-31.1

Cookie preferences