Getting Started with Ternary Operators in Javascript

Introduction
In my last blog post, I wrote about using switch statements when I don't need complicated if-else
statements. It makes my code easier to read and overall just easier to manage. In keeping up with trying to clean up my conditional statements, I have been implementing more ternary operations into my code. Now I have usually avoided them just because I was just used to writing if-else
statements, but honestly, less is more and if you don't need to type out a multiline statement, why not use a ternary operator? Let me show you why they are great!
To write a ternary operator:
<ConditionalStatment> ? <executeThisIfTrue> : <executeThisIfFalse>
You write the condition that you are testing for first and then it is followed by a question mark ?
. What follows the question mark is what will run if your condition is true
. This acts as the if
statement block. We then use the colon :
as the mandatoryelse
statement and we precede to write the code that will execute if the condition is false
.
Let’s look at some code.
Code
On line 3, my condition is checking whether the age
variable is greater than or equal to 18. If it is, console.log
“I can vote”. Otherwise, console.log
“I cannot vote”. Since the ternary operator is an expression, it will give you a value. This makes conditionally assigning variables a value easier than writing it within a traditional if-else
block.
For example:
The variable votingAge
will be assigned a value based upon the condition in our ternary. If we wanted to do this with an if-else statement we would have to do a little more work. If we want to declare the variable for the if-else
statement, we should declare it outside of the block like so:
As you can see, there is a stark difference in how much quicker it is to write the ternary vs the if-else
block and it can all be done in one line. I don't have to declare the variable in one place and then write out the assignment over and over as I do on lines 6 and 8 if the condition is true or false. With the ternary, I can do it all at once on one line.
And that is not the only thing! We are also able to use ternary operators within template literals since they are expressions.
The template literal will use whatever value is resolved from the condition and put it into our string.
Now, the ternary is not a replacement for if-else
statements. We will still need them when we need more lines of code, possibly want to return a value, for those times that you do not even want an else statement or other reasons your code may need. The ternary is meant to be for those instances where writing out an if-else
is unnecessary for a basic condition.
Conclusion
I hope that was helpful in getting started with the ternary operator. If you have more questions, I suggest going through the MDN docs and other resources.