JavaScript Ternary Operator

By

Published · Updated

Tagged: JavaScript

Learn how the JavaScript ternary operator gives you a short way to write a conditional with three operands, choosing one of two expressions to run.

The ternary operator is the only operator in JavaScript that works with 3 operands, and it’s a short way to express conditionals.

This is how it looks:

<condition> ? <expression> : <expression>

The condition <condition> is evaluated as a boolean, and upon the result, the operator runs the first expression (if the condition is true) or the second.

This is an example: we check if running equals to true, and if this is the case we call the stop() function. Otherwise we call the run() function:

const running = true;
(running === true) ? stop() : run()

The ternary returns a value

This is the big difference from if. An if is a statement: it runs code. The ternary is an expression: it gives back a value, so you can assign it, return it, or put it inside other code.

const age = 26
const drink = age >= 21 ? 'Beer' : 'Juice'
//'Beer'

The same with if needs more lines and a let:

let drink
if (age >= 21) {
  drink = 'Beer'
} else {
  drink = 'Juice'
}

That’s where the ternary shines. In the first example above, where we just call stop() or run() and ignore the result, a normal if is easier to read.

You can use it inside a template literal:

const items = 1
console.log(`You have ${items} ${items === 1 ? 'item' : 'items'}`)
//You have 1 item

Or in a return:

function getFee(isMember) {
  return isMember ? '$2.00' : '$10.00'
}

It’s also the common way to choose between two pieces of UI in JSX, see conditional rendering in React.

Truthy and falsy conditions

The condition doesn’t have to be a boolean. Any value works.

These values are “falsy” and pick the second expression: false, 0, '' (empty string), null, undefined and NaN. Everything else is “truthy” and picks the first one.

const person = null
const name = person ? person.name : 'stranger'
//'stranger'

This is handy, but watch out for 0 and ''. They are often valid values:

const count = 0
count ? count : 'none' //'none', but 0 is a real count!

If you only want a fallback for null and undefined, use the nullish coalescing operator instead:

count ?? 'none' //0

Chaining ternaries

You can chain ternaries to check more than one condition, like an if / else if / else:

const score = 72

const grade = score >= 90 ? 'A'
  : score >= 80 ? 'B'
  : score >= 70 ? 'C'
  : 'F'
//'C'

Put each condition on its own line like this, or it gets hard to read very quickly. With more than 3 or 4 cases, I’d switch to if statements or a switch.

Avoid nesting a ternary in the first part, like a ? (b ? x : y) : z. It works, but nobody wants to read it.

Common mistakes

Precedence. The ternary has a very low priority, so the code on its left runs first. This doesn’t do what it looks like:

const isMember = false
'Total: ' + isMember ? 2 : 10
//2

JavaScript first does 'Total: ' + isMember, which is the string 'Total: false'. That’s truthy, so you get 2. Wrap the ternary in parentheses:

'Total: ' + (isMember ? 2 : 10)
//'Total: 10'

You can’t put statements inside. Both sides must be expressions. return, throw, if and const are statements, so this is a syntax error:

const value = ok ? 1 : throw new Error('no') //SyntaxError

Use an if in this case.

You always need both sides. There’s no ternary without the : part. If you only need the “true” case, use an if, or condition && doSomething().

Want me to talk about your product? You can sponsor this site.

Related posts about js: