top of page

How to use the ternary operator in JavaScript

The ternary operator is a simpler and shorter version of the if/else conditional operator. Ternary is probably not a word you use a lot, at least if English is not your everyday language, so you might hear people ask about the conditional operator or the ?: (question mark colon) operator.

​

Just as the if/else the ternary operator evaluates a condition to either true or false and then flows in one of those directions. The ternary operator syntax like a compact if/else. Let's look at the syntax.

So if the condition is boolean true then expression-true will be executed. If the condition evaluates to boolean false, then expression-false will be executed. Just like if/else, the condition is evaluated to be either true or false and then follow the flow accordingly to the outcome of the condition.

​

Let us show you with some actual code. In this example we will check if someone pass a certain score, and let's say 100 is the score to beat. Using the ternary operator the code could look something like this. 

Let's look at what the code does. It takes a variable score and checks if it is 100 or more. This is the condition, score >= 100.

Based on if the condition is true or false it choose one of the expressions after the question mark (?), if it's true it selects the one on the lift side of the colon (:), if false it selects the one on the right side.

​

We will now look at how the same code would look like if we used if/else instead of the ternary operator. This code show the same solution as the example with ternary operator, but this time with if/else.

So what we see is that the ternary operator does the same as if/else, but with a much more compact code. It's shorter and simpler than the good old if/else.

​

All this looks good and you might think that you can swap out all the old if/else with the ternary operator? But then you might think about if/else with multiple else statements, what then?

​

There is a solution for this, you can nest ternary operators. Again, let us look at an example. This time we start with the if/else code.

​

In this example we will make the user know that they did great and almost got to the success score.

Now this is much more complicated, so how will this look with the ternary operator? Let's have a look at the code.

It's still the same result and both examples does the same, but this time the ternary operator example was not as easy to read. 

​

The ternary operator is a way to make your code more compact and more readable, but if the code get's too long or if you start to nest the ternary operator the code might get harder to read.

​

bottom of page