Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double ternary in JavaScript

Tags:

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??

like image 708
Sethen Avatar asked Jan 20 '13 18:01

Sethen


People also ask

Can you put a ternary inside a ternary?

For example, you should not try to make ternary operators nested inside of ternary operators.

Can you chain ternary operators?

A Ternary Operator in Javascript is a special operator which accepts three operands. It is also known as the "conditional" or "inline-if" operator. Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block.

Can you have nested ternary operator JavaScript?

You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.

What does ternary mean in JavaScript?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


2 Answers

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);
}
like image 162
Niet the Dark Absol Avatar answered Sep 18 '22 09:09

Niet the Dark Absol


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;
}
like image 35
Kevin Bowersox Avatar answered Sep 22 '22 09:09

Kevin Bowersox