Just the weekly tutorials.

JavaScript Ternary / Conditional Operator

The JavaScript's Ternary (also known as Conditional) operator executes a JavaScript statement based on a condition of another statement. If the main statement evaluates to the Boolean value of "true", one predetermined statement is returned. If it evaluates to "false" a secondary statement is returned. In this example we will take a look at creating a mixed string of text and numeric values, modifying a word's trailing "s" character.

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 0 times
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.

Ternary operator to the rescue. This ternary operator, also known as the conditional operator, is of use here. It allows us to skip writing a JavaScript function that compares numbers and returns a value. Instead, we can simply do everything on a single line of code.

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:

statement1 ? statement2 : statement3

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.

Using the Ternary operator we tell JavaScript to check whether the value stored in the variable "times" is equal to a value other than 1. Notice the question mark. If so, simply type the value that needs to be returned. In this case "s". If the numeric value is 1, then instead of an "s" we get an empty space.

Just the weekly tutorials.