Sethen
Sethen

Reputation: 11348

Double ternary in JavaScript

I was going through some stuff in the jQuery source, specifically the inArray method and I found this line of code:

i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

What I am seeing is two ternary operators, but I have no idea how this is used. I understand how the ternary operator works, but I have never seen it used like this before. How does this piece of code work??

Upvotes: 18

Views: 35135

Answers (4)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Just break it down like you would 1 + 2 + 3:

if (i) {
    if (i < 0) {
        i = Math.max(0, len + i);
    } else {
       i = i; // no-op
    }
} else {
    i = 0; // also no-op, since if `i` were anything else it would be truthy.
}

In fact, that whole line seems inefficient to me. Personally I'd just use:

if (i < 0) { 
    i = Math.max(0, len + i);
}

Upvotes: 23

Balaji Sivanath
Balaji Sivanath

Reputation: 506

i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

reads to

i = i ? ( i < 0 ? Math.max( 0, len + i ) : i ) : 0;

Upvotes: 3

Gato
Gato

Reputation: 671

By any chance, is "i" an index into an array and "len" the length of the array?

If it is so, then that line would do the following:

  • if i can be equated to false, then assume it's 0

  • else if i is positive or 0, then take it as it is

  • else if i is negative, then consider it an index counting from the end of the array (ie. if i==-1, it means the last element of the array).

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

Breaks down to:

var i;

if(i){
  if(i<0){
   i = Math.max(0, len + i);
  }else{
    i = i;
  }
}else{
  i = 0;
}

Upvotes: 11

Related Questions