It is common for web applications to mix numbers and strings to display a message that tells how many times an action has taken place. The message displayed could contain a numeric/word combination such as: “0 times”, “1 time”, “25 times”, and so forth. We need to determine whether the “s” character needs to be present in some of the cases, and absent in some others. An example of a message follows below:
The message was displayed 1 time
The message was displayed 7 times
In order to keep correct sentence structure the trailing “s” in the word “time” needs attention.
The basic design of the ternary operator includes 3 statements separated by a question mark ? and the colon character : and it can be expressed as follows:
If statement1 evaluates to true, return statement2. Otherwise, if statement1 evaluates to false, return statement3.
Now let’s apply this logic to our problem. We need to figure out whether there is a trailing “s” at the end of a word or not, based on which numbers it was used in combination with. We need to determine some type of a formula, or a plan of action.
Trying all kinds of combinations you will finally arrive at the following conclusion. Unless the numeric value is 1, we must add “s” to the word “time” to be on good terms with the English language syntax.
// decide whether to display a trailing 's' after string 'time' var times = 7; var trailing_s = (times != 1) ? 's' : ''; // this message will display "7 times", notice the trailing "s" alert(times + "time" + trailing_s);
Of course, this is not the only use of the ternary operator. The possibilities are endless. However, this is a perfect case for demonstrating its function.