1. Technology

JavaScript By Example

13. Ternary Operator


Man Sitting At Desk Using Computer
Cavan Images/Stone/Getty Images

There is one further way if which you can perform comparisons in JavaScript and that is using what is known as the ternary operator. It is called the ternary operator because unlike all the operators where the opterator goes between two values, this operator actually requires a third value to be placed in the middle of the operator.

The ternary operator is a substitute for an if statement where both the if and else clauses assign different values to the same field - like this:

if (condition)
  result = 'something';
  result = 'somethingelse';

The ternary operator shortens this if/else statement into a single statement.

result = (condition) ? 'something' : 'somethingelse';

While this particular substitution can only be done where the original if statement follows the format shown above this is in fact one of the more common situations where an if statement is needed and the ternary operator is the more efficient way of coding this construct since when coded using the ternary operator it is obvious that one of two values is to be loaded into the result field where the content of an if statement can be anything at all.

Note that you can nest ternary operators since the second and third positions can have anything that returns a value substituted for them.

Note that to test this example try adding a ? followed by a colour to the end of the address of the page - example13.html?red


<title>Example 13</title>
<p id="ex"></p>
<script type="text/javascript" src="example13.js"></script>


var colour, favcol;
colour = window.location.search.substring(1);
favcol = ('green' === colour) ? 'is green.' : 'is not green.';
document.getElementById('ex').innerHTML = colour + favcol;

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Ternary Operator

©2014 About.com. All rights reserved.