Skip to content

Ternary Operator

The ternary operator, also called the conditional operator, chooses between two values. It takes three operands, which is where the name comes from:

condition ? valueIfTruthy : valueIfFalsy

JavaScript tests the condition, and the whole expression then takes the value after ? if the condition is truthy, or the value after : if it is falsy. Only the chosen side is worked out.

const stock = 0;
const label = stock > 0 ? 'In stock' : 'Sold out';
console.log(label);

This prints:

Sold out

The same choice with if and else needs a let declared first and an assignment in each branch. The ternary is an expression, so it produces a value that can be stored, returned or passed straight to a function, which if cannot do.

That also makes it useful inside a template literal:

const count = 1;
console.log(`You have ${count} ${count === 1 ? 'book' : 'books'} on loan.`);

This prints:

You have 1 book on loan.

A ternary can go in the falsy branch of another, which gives a chain like else if. Laid out one condition per line, it reads as a table:

const describe = (celsius) =>
celsius < 0 ? 'freezing'
: celsius < 15 ? 'cold'
: celsius < 25 ? 'mild'
: 'hot';
console.log(describe(-3), describe(9), describe(18), describe(31));

This prints:

freezing cold mild hot

As with else if, the conditions are tested from the top and the first match wins. Nesting a ternary inside the truthy branch, or writing a chain on one line, is much harder to follow, and an if and else if chain is then the clearer choice.

Use the ternary when both branches produce a value. A line such as paid ? sendReceipt() : sendReminder() works, but it uses an expression only for its side effects, and an if statement states that intention more plainly.

Steve Griffith covers this topic in his video Javascript Ternary Operator.