Andre Bulatov Andre Bulatov - 4 months ago 9
Javascript Question

How to read two shorthand if statements connected with an equal strict?

I was looking through moment.min.js when I ran into an expression that looked like this:

return A ? B : C === D ? E : F


Literally, I would read that as
when this function is called, return the result of if A then B, else C, must strictly equal if D then E, else F
, but even if that's correct, I am not sure exactly what that does.

How is that read and what would the expression do?

Answer
return A ? B : ((C === D) ? E : F);

Maybe it's easier to understand with those parentheses (evaluates to the same). The exact representation of the code above with if-else statements are:

if (A == true) {
   return B;
} else {
   if (C === D) {
     return E;
   } else {
     return F;
   } 
} 

I could also write return (A ? B : ((C===D) ? E : F)); The point is that if A wont evaluate to true, then another ternary operator is evaluated. Those parentheses just separate them from the other one, but they are absolutely not neccessary.

return (A ? B : C) === (D ? E : F); In this case we compare the evaluation of two ternary operators, and return it's result, which is a completely different story.