DEV Community

Sahil Thakur
Sahil Thakur

Posted on

Ternary operator in Javascript with examples

This post is originally written here with code images as well -> https://easyontheweb.com/the-ternary-operator-in-javascript-with-examples/

Without a shadow of a doubt one of the coolest and sleekest features of Javascript is the ternary operator. I guess the first time I used it was while coding in C in college and I’ve been using it ever since. In this article we’ll see how to use and more importantly how now to use the ternary operator in Javascript with examples.

We’ll look at the syntax and workings of the ternary operator in the next section and then will proceed into when we should use this operator and then into when we should not use this operator (I actually find that’s an even more important thing to discuss now). Just as a bonus section I’ll discuss how I also like using it in React as well.

What is the ternary operator
Okay, so to make things clear ternary operator is not a concept that is just there in Javascript. It is found in many other languages and is a very popular way to write cleaner code.

The ternary operator actually is nothing but something we call syntactic sugar in programming language. What this means is that it is not some syntax that does something new but actually is a cleaner way to write something that can be written following some other syntax.

The previous paragraph is the most confusing thing I’ve ever written so let me rephrase this in a little easier language. Ternary operator is nothing but a cleaner way to write something that can be written in some other manner and the something being referred to here is if-else.

Conditionals are one of the most important parts of coding in general and ternary operator gives us a cleaner way to write those conditionals. A normal if else statement might take up more lines of code than it actually needs to. Even if the business logic inside if-else is of one line each, we take up anywhere from 2 to 6 lines of code depending on how you write the brackets in conditionals.

This is where ternary makes the code clean and easy to read. It performs the same if-else logic in a single line of code. Let us see how in the next section.

Using the ternary operator
In this section we’ll actually be doing what the title of the post says and seeing the ternary operator in usage in Javascript with examples.

Actually, you can use the ternary operator just about anywhere you would use the if-else conditionals and it would work the same way but I personally look to use it for two major things – assignment to variables and returning something.

Assignment to variables -> One of the most widely adopted uses of the ternary operator and a place where it’s usage actually makes a lot of sense is the assignment of some value to a variable.

Assume that there is a variable called noOfUsers which can take up two different values depending on a condition, say, if an argument onlyTeenagers is true or false. Let us see both ways of assigning value to this variable.

Usage of ternary operator
For anyone who does not know the working of the ternary operator , it is actually quite simple -> Think of it consisting of three parts (hence the name ternary), the first part is a conditional that must return a boolean (or will be typecasted to a boolean), if that boolean is true that means the expresseion after the ? and before the : will be executed. If that boolean is false, then the expression after the : will be executed.

So, in this example of ours if the onlyTeenagers boolean is true, we execute the function findTeenageUsers and assign it’s value to the noOfUsers variable, if the onlyTeenagers boolean is false, we execute the findAllUsers function and assign it’s value instead.

We can also see how the if-else version of the same code takes up 6 lines to write (The way I write if-else that is) and the ternary operator does the same in a much more compact manner in a single line.

Another use case very similar to the above one where I love using the ternary operator is to return values from a function when based on a conditional.

As you must have figured out, the if else version of the same would have been a lot longer than this one using the ternary operator where we just return a value based on the condition of onlyTeenagers (the values 50 and 75 are purely random).

Another thing you should keep in mind is that ternary operators can also do multiple operations separated by a comma in this way :-

I’m not a big fan of doing it this way but this can be done, no issues.

When not to use the ternary operator
Now that we have seen the cases when we should use the ternary operator, let us also see the cases when not to use the ternary operator. Actually, it’s not even cases but just a single case that then roots down to many different cases ahead.

That case is of nested conditionals. Trust me, don’t JUST DON’T use ternary operators if you have nested conditionals. Even though more if-else conditionals will take up more LOC I would still prefer to that than clutter my single line of code with nested ternary conditions.

A single line of code that has multiple ternary conditionals remind me of callback hell to be honest. They are difficult to read and comprehend and just go against the very thing ternary operator was created for – better readability.

Not saying that people don’t use nested ternaries, they do – but it’s ugly and certainly not recommended. I won’t even give an example of nested ternary operators here because they are just too ugly 😛

Using ternary operator in React (JSX)
This is just an additional section for devs who work on React or want to work on React in the future.

Well, React renders content using JSX and there are many many times when we want to render content based on some condition and we add that conditional check in the JSX itself. Now, JSX allows us to use Javascript code inside something much more closer to HTML.

What I use the ternary operator for is to show a certain element or component on the screen if the condition is true and some other component on screen if the condition is false.

Let us take an example. Assume that we want to show a different component based on whether the age of the user is greater than or less than 25. This is how I would write the code for the JSX :-

I hope you did learn a few tips and tricks regarding the ternary operator in this article and you do apply them in your coding. Please comment any tips you want to share regarding this.

For other Javascript related articles please check them out here -> https://easyontheweb.com/category/javascript/

Top comments (0)