The Ternary Operator: Shorthand for if/else

I ran into this when going through a slideshow tutorial from Six Revisions, so I thought I would find out what it was and how it worked.

Here’s the snippet from that slideshow tutorial that contains the ternary operator:

currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;//Determine new position

What It Is

A ternary operator is basically shorthand for if/else. Wayne Koorts explains it simply. It “should produce a boolean result when evaluated: either true or false.” He gives this example:

<variable> = <expression> ? <true clause> : <false clause>

So in the slideshow example, it determines currentPosition. If rightControl is true, it sets currentPosition+1. If false, it sets it at currentPosition-1. Simple as that.

Example

I could write an if/else statement like this:


var a = 8;
var b = determineA();

function determineA(){
  if (a <=11){
    return "blue";
  } else {
    return "green";
  }
}

console.log(b);//returns "blue"

Or, I could simplify that by using a ternary operator like this:


var a = 8;
var b = (a <= 11) ? "blue" : "green";
console.log(b);//returns "blue"

Sources:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>