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??
For example, you should not try to make ternary operators nested inside of 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.
You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator 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.
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);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With