alert(“There is ” + x + ” apple”);
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”;
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 web design/development tutorials. Have an amazing day!