Ternary operators

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Ternary operators

Earlier, you learned that if/else statements let you create conditions to determine how code should run. You can, for example, write code that makes a person walk() when they see a green light; and make the person stop() when they see a red light.

if (isLightGreen) {
  walk()
} else {
  stop()
}

if/else statements have their downsides as well. It forces you to think about two things at once, which can be taxing and confusing.

To see why if/else statements can be taxing, consider programming like watching cars on a road. You need to keep track of each car.

When you see an if/else statement, you make a fork in the road. When the road forks, you need to track each car in two places. Tracking cars on two roads is more taxing than on a single road. Yup?

A forked road
Tracking cars in two places is more taxing

There’s a simpler alternative—a ternary operator.

A ternary operator lets you write if/else statements in an easy-to-read manner. If we use the “watch the cars” analogy mentioned above, a ternary operator creates a fork that merges quickly, allowing you to watch one road.

A fork that was closed quickly
You can close the fork quickly with ternary operators

Let’s see how a ternary operator works.

The syntax of a ternary operator

Ternary operators consist of three parts:

  1. The condition—the same condition in an if/else statement
  2. The truthyExp—the statement to execute when the condition is truthy
  3. The falseyExp—the statement to execute if the condition is falsey

It looks like this:

condition ? truthyExp : falseyExp

Let’s compare the “traffic light” example earlier with if/else statements and ternary operators. You’ll see the difference between them immediately.

// Traffic light example with if/else
if (isLightGreen) {
  walk()
} else {
  stop()
}
// Traffic light example with Ternary operators
isLightGreen ? walk() : stop()

As you can see, you can shorten five lines of code (from if/else) to one line of code if you use ternary operators.

If you wish to, you can place ? and : in their own lines. When you do so, ternary operators look like a simplified version of their if/else counterparts.

isLightGreen
  ? walk()
  : stop()

When to use ternary operators

You want to use ternary operators over if/else statements when your if and else branches contain one expression each.

Nest up to two levels

You can nest ternary operators for more complicated decision making processes, but you don’t want to nest more than two levels, because it’ll get complicated.

For example, let’s say you want to buy a toy for your friend’s baby. Here’s what you decided:

  1. If the baby is a boy
  2. if he is born in December, get him a santa sock.
  3. if he is not born in December, get him a toy car.
  4. If the baby is girl
  5. if she is born in December, get her a candy cane.
  6. if she is not born in December, get her a doll.

You can write the above conditions with if/else statements, like this:

let toy
if (gender === 'boy') {
  if (birthMonth === 'December') {
    toy = 'santa hat'
  } else {
    toy = 'toy car'
  }
} else {
  if (birthMonth === 'December') {
    toy = 'candy cane'
  } else {
    toy = 'doll'
  }
}

Here’s what it might look like if you use ternary operators.

const toy = gender === 'boy'
  ? birthMonth === 'December'
    ? 'santa hat'
    : 'toy car'
  : birthMonth === 'December'
    ? 'candy cane'
    : 'doll'

Exercise

  1. Which function executes in the code below? walk() or stop()?
const lightColor = 'red'

lightColor === 'green'
  ? walk()
  : stop()
  1. Find the index of apple in the fruitBasket. Then, use a ternary operator to decide between two functions, eat() or wash(). If the index of the apple is 2, run eat(). Otherwise, run wash().
const fruitBasket = ['apple', 'pear', 'orange']
  1. What is finalNum in the following code?
const num = 5
const square = num => num * num
const add = num => num + num

const finalNum = num > 5 ? square(num) : add(num)

Answers

  • Which function executes in the code below? walk() or stop()?
const lightColor = 'red'

lightColor === green
  ? walk()
  : stop()

Answer: stop()

  • Find the index of apple in the fruitBasket.
  • Then, use a ternary operator to decide between two functions, eat() or wash().
  • If the index of the apple is 2, run eat(). Otherwise, run wash().
const fruitBasket = ['apple', 'pear', 'orange']
const index = fruitBasket.indexOf('apple')

index === 2
  ? eat()
  : wash()
  • What is finalNum in the following code?
const num = 5
const square = num => num * num
const add = num => num + num

const finalNum = num > 5 ? square(num) : add(num)

Answer: 10