First Principles
Programming

Ternary Operator in JavaScript

The ternary operator — a one-line shorthand for if-else, where it shines, and where a plain if-else reads better.

By Fadjar Rafi. Published 26 Nov 2024. 2 min read.

Contents
  1. Where it's handy
  2. Don't nest them
  3. A couple of gotchas

The ternary operator is a one-line shorthand for if-else. It's the only JavaScript operator that takes three parts — a condition, a value for when it's true, and a value for when it's false.

condition ? valueIfTrue : valueIfFalse
The three parts of a ternary: condition, value if true, value if false

The key difference from if-else is that a ternary is an expression — it evaluates to a value you can assign:

const basket = 'apple'

// if-else
let result
if (basket === 'apple') {
  result = 'This basket has apples'
} else {
  result = 'This basket has no apples'
}

// ternary — same thing, one line
const result = basket === 'apple' ? 'This basket has apples' : 'This basket has no apples'

Where it's handy#

Assigning a value based on a condition, or returning one from a function, is the sweet spot. It's especially common in React for picking a component or a class name:

return <div>{isLoggedIn ? <UserDashboard /> : <LoginForm />}</div>

<button className={isActive ? 'btn-active' : 'btn-inactive'}>Click me</button>

For a plain default value, reach for ?? (nullish coalescing) instead — it's clearer and only falls back on null or undefined:

// works, but wordy
const name = user.name ? user.name : 'Guest'

// better
const name = user.name ?? 'Guest'

Don't nest them#

You can chain ternaries, but readability falls off a cliff fast:

const result =
  basket === 'apple'
    ? 'This basket has apples'
    : basket === 'banana'
      ? 'This basket has bananas'
      : 'This basket has no fruit'

Once there's more than one condition, if-else (or a switch) is easier to follow:

if (basket === 'apple') {
  result = 'This basket has apples'
} else if (basket === 'banana') {
  result = 'This basket has bananas'
} else {
  result = 'This basket has no fruit'
}

A couple of gotchas#

Keep both branches the same type — mixing a string with false leads to surprises down the line:

const result = isValid ? 'Valid' : false // avoid
const result = isValid ? 'Valid' : 'Invalid' // clearer

And use it for values, not side effects. If each branch does something rather than returns something, use if-else:

// don't
isLoggedIn ? saveUserData() : showLoginForm()

// do
if (isLoggedIn) {
  saveUserData()
} else {
  showLoginForm()
}

The rule of thumb: a ternary should make a line easier to read at a glance. The moment it doesn't, an if-else will.