javascript ant

RSS or Atom

 

Piles of javascript goodness
 

The Conditional Operator (Ternary Operator)

 

JavaScript has only one unique operator, the conditional operator. This operator is often referred to as the ternary operator because it takes three operands. This should not be confused with the fact that the conditional operator only has two operators ("?" and ":"). These two operators separate three operands. It looks like this:

first ? second : third

The conditional operator functions similar to the if-else statement. So, in order to understand the conditional operator, let's have a look at an if-else statement first. Hopefully the following example is familiar to you.

The above if statement simply checks to see if the variable answered has a string value of 'yes'. If it does, then it will evaluate the first statement (alert('you\'ve answered');). Now, if the value of the variable answered is equal to 'no', then the if statement would evaluate the second statement (alert('you haven\'t answered');).

The conditional operator functions in the same exact manner. Here is the code that produces the same outcome as the if-else statement, but using the conditional operator.

Now, besides being more compact, the great thing about conditional operators is you can use them in expressions. That is, you can have them appear on the right side of an operator to perform a choice when you need to select one of two values. This means you can directly store the results in a variable.