Some of the most useful “utilities” in any programming languages are the conditional statements. Conditional statements help a lot in making the piece of code dynamic and intelligent. In fact it would not be an exaggeration to say that without conditional statements none of the software and web applications would be existing today. Javascript too has conditional statements. In this article we will look into ternary operators, which is a conditional operator.

What is a ternary operator ?

As per the Oxford english Dictionary the term Ternary means “composed of three parts” . As the name suggests, Ternary operators are composed of three parts : Condition ? Expression 1 : Expression 2 . Hence we can say that :

Ternary operator is a conditional operator composed of three parts; the Condition, First Expression and Second Expression. If the condition evaluates to True, it returns the value of the First Expression else it returns the value of the Second Expression.

It is very similar to the If…Else statement. Let us understand it with the help of an example.

Nested Ternary operator

Like in case of an if…else statement, the ternary operators can also be nested. Let us look at the following if…else statement first

In the above example you’ll notice that we have an if-else condition within the if block. The first if condition checks if the user is above¬† 17 yrs, and if true , we further check if he/she is single. The variable Eligibility gets updated accordingly. Now lets write the same condition using ternary operator.

As you must have noticed, using ternary operator makes the code shorter and manageable (if formatted properly). It is in fact much easier than if-else statement. It also helps in improving the file size by avoiding multiple lines. At the same time not every if-else statement should you replace with ternary operators. Do it wisely.

I would suggest using ternary operator wherever possible and in case you feel that the nesting is going to get complex then you may use if-else statement. Though you can actually break ternary condition and expression onto multiple lines to maintain readability.

Happy Coding ! :)