How To Use The Ternary Operator in JavaScript
JavaScript, Uncategorized, Web Design
In JavaScript, there is a thing called the ternary operator. It’s a fancy term for a shorthand way to write an if statement. To compare and contrast let’s take a look at the long way of creating an if statement:
if(x==1){
alert(“There is ” + x + ” apple”);
}else{
alert(“There are ” + x + ” apples”);
}
This example is checking the value of x and if it’s 1 it will alert “There is 1 apple”. If it’s not 1, it will alert, “There are 3 apples” or whatever the number is that was put in there. Well, there’s a shorter, easier way to handle this using the ternary operator. This is how the ternary operator is set up:
var tern = condition ? do this if true : do this if false;
There is a variable set up and its set equal to the ternary operator. The first part is the condition, then a question mark, then what will happen if the condition is true, then a colon separating what will happen if it’s false. So we could set up our example like so:
var tern = x==1 ? “There is ” + x + ” apple” : “There are ” + x + ” apples”;
alert(tern);
If x is one it will set tern equal to “There is 1 apple” and alert that. If it’s not 1 then it will set to tern equal to “There are however many apples” and alert that. Pretty useful I must say. If you’d like to learn more be sure to check out our JavaScript Training. Have an amazing day!