Ternary operator in Javascript

What is the Javascript ternary operator, also called conditional operator, with usage examples and recommendations.

After having known the most important ones, we are going to approach another relevant operator, although not so used. This is the Javascript ternary operator, which is very useful on a day-to-day basis when we want to get a possible value depending on a conditional expression.

What is the ternary operator

The ternary operator can be understood as a compact structure to make conditionals. It consists of an expression that will be evaluated and, depending on whether said evaluation was positive or negative, it will return one or the other.

Its syntax is the following:

conditional_expression ? expression1 : expression2;

The “conditional_expression” will be the one that is evaluated, positively or negatively. “expression1” will be executed if it is positive and “expression2” will be executed if it was negative. Additionally, as a result of the execution of the ternary operator, what is returned by the expression finally executed (1 or 2) will be returned.

This conditional operator is known as a ternary because it has three operators, both the conditional expression to evaluate and two expressions to execute for the positive or negative case.

Let’s see an example of use:

(x < 1000) ? x : 1000;

That code will return the value of x if the variable x was a number less than 1000. Otherwise (x was not less than 1000) it will return 1000.

Since this statement ends up returning the value that is the result of one expression or another, it is common for it to be used in conjunction with an assignment statement.

See also  sequential structures

var value_x_limited_to_1000 = (x < 1000) ? x : 1000;

When executing the previous line of code we will have a variable called “value_x_limited_to_1000” that will contain the value of x or, if x exceeds 1000, it will contain the value 1000.

For another example, we could get the name of a day of the week, making sure that we are given a correct day number. To build this example we need to have an array with the numbers of the week;

var weekDays = ;

Then we could use the ternary operator like this:

var day = (numberOfDay < weekDays.length) ? weekDays : 'wrong day';

The complete code of a script that could be used to test this sentence could be the following:

var daynumber = 3; var weekDays = ; var day = (numberOfDay < weekDays.length) ? weekDays : 'wrong day'; console.log(day);

As you have seen, we have achieved a very compact behaviour. Without using the ternary operator we could also have obtained a valid result but with more lines of code. Let’s see this same behavior with a lifetime if.

var daynumber = 3; var weekDays = ; if (dayNumber < weekDays.length) { var day = weekDays; } else { var day="wrong day"; } console.log(day);

Recommendations for using the conditional operator

This operator is very powerful, since it achieves quite broad behavior for the little code used. However, sometimes the result is not as clear as a simple “if” might be.

Therefore, we must use it with caution, analyzing whether it is really necessary or not, as well as whether it really facilitates the reading of the code and therefore its maintenance, or on the contrary, makes it worse.

For example, let’s go back to the example of the number limited to 1000. How would we go about handling the special case where something other than a number is returned? We want you to control:

  • If it’s not a number, we want the value 0
  • If it’s a number, we want it to limit it to 1000 at most
See also  Forms and Javascript

We could express this logic like this:

var constrained = (isNaN(x)) ? 0 : (x < 1000) ? x : 1000;

I don’t know if you will agree that the sentence is beginning to be unclear. Maybe the strategy should be changed to something simpler like:

var constrained if(isNaN(x)) { constrained = 0; } else { constrained = (x < 1000) ? x : 1000; }

These two codes are equivalent. The second alternative clearly has more code, but perhaps for many people it is clearer than the first. Looking at the if, it’s clear that we first want to check if it’s not a number, in which case the bounded value will be 0. Then, if it was a number, then the bounded value of 1000 is returned.

To give another type of example. We want a function that tells us if a number is even or odd. The code could be this:

function isPar(value) { return value % 2 == 0 ? true: false; }

What do you think of that code? is it clear enough?

It is a trick question, because in this case the problem is not clarity, it is that the conditional operator is really unnecessary. We could have simply written this:

function isPar(value) { return value % 2 == 0; }

conclusion

We have learned to use the ternary operatoralso called conditional operator, from javascript. It is a useful tool because of its power and the ability to implement a conditional operation with little code.

You will find this operator in many other programming languages, which is why it is very widespread. It is important that you know it and have it on hand to use it when it really helps to create a more summarized code, always carefully so as not to lose its ease of reading and understanding.

Loading Facebook Comments ...
Loading Disqus Comments ...