Skip to content
Advertisement

What does return void 0 === i && (i = 3), 0 === i ? ( ..A.. ) : ( ..B.. ) do?

I came to this code but I don’t understand very well what it does..

test.update = function(i) 
{ 
return void 0 === i && (i = 3), 0 === i ? (..A..) : (..B..) 
}

(..A..) and (..B..) are just other lines of code I haven’t posted.

Let’s say if i would have a 0 value, what the function will return?

What does “void 0 === i && (i = 3)” do? Specially (i = 3). Does that mean that if (void 0 === i) is true and i can get 3, i will be 3? And what about the comma? I’ve checked this question but I still don’t get it.

Sorry for so many questions but I’d like to have a complete answer so I can totally understand what is going on.

Thank you

Advertisement

Answer

Okay, first let’s set brackets according to operator precedence:

return (((void 0) === i) && (i = 3)), ((0 === i) ? A : B)

Now to the single operations

void 0

simply returns undefined. We could also write it this way:

undefined === i

which obviously checks whether i is undefined.

i = 3

looks like a comparison first, but in fact it’s an assignment that returns 3. So far the line looks up whether i is undefined and in case it is, it is assigned the value 3.

Now the following comma is an operator on its own. It evaluates all expressions from left to right and returns the last one (right-most). In this case the last expression is a comparison of 0 and i. Means if i is 0 at this point, the return value of the whole expression is true.

As last there comes a conditional operator which is a short way to write if .. else ...

So far the line could have been also written as:

if (i === undefined) {
  i = 3;
}
if (i === 0) {
  // return ( A )
}
else {
  // return ( B )
}
Advertisement