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?
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.
Let’s see how a ternary operator works.
The syntax of a ternary operator
Ternary operators consist of three parts:
- The
condition— the same condition in anif/elsestatement - The
truthyExp— the statement to execute when the condition is truthy - The
falseyExp— the statement to execute if the condition is falsey
It looks like this:
condition ? truthyExp : falseyExpLet’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/elseif (isLightGreen) { walk()} else { stop()}// Traffic light example with Ternary operatorsisLightGreen ? 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:
- If the baby is a boy
- if he is born in December, get him a
santa sock. - if he is not born in December, get him a
toy car. - If the baby is girl
- if she is born in December, get her a
candy cane. - if she is not born in December, get her a
doll.
You can write the above conditions with if/else statements, like this:
let toyif (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
- Which function executes in the code below?
walk()orstop()?
const lightColor = 'red'
lightColor === 'green' ? walk() : stop()- Find the index of
applein thefruitBasket. Then, use a ternary operator to decide between two functions,eat()orwash(). If theindexof the apple is 2, runeat(). Otherwise, runwash().
const fruitBasket = ['apple', 'pear', 'orange']- What is
finalNumin the following code?
const num = 5const square = num => num * numconst add = num => num + num
const finalNum = num > 5 ? square(num) : add(num)-
Which function executes in the code below?
walk()orstop()? — Stop. -
Find the index of
applein thefruitBasket. Then, use a ternary operator to decide between two functions,eat()orwash(). If theindexof the apple is 2, runeat(). Otherwise, runwash().
const fruitBasket = ['apple', 'pear', 'orange']const index = fruitBasket.indexOf('apple')
index === 2 ? eat() : wash()- What is
finalNumin the following code? — 10
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson