简体   繁体   中英

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?

It test if A is truthy (a number !== 0, a not empty string, an object, not null , not undefined ) then return B . If not, then check if C is strict equal D , return E otherwise F

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

Apply syntax precedence, to get:

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

Is A truthy? Yes? Great, return B .

Oh, it's not? Then depending on whether C is strictly equal to D , return either E or F .

The author should not have written such confusing shorthand, and this question is why.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM