Buggy compiler behavior

I get different results when running the following piece of code:

  return (!talliedWeek && level  < 4)                     ?  0 :
         (!talliedWeek && level >= 4)                     ? -1 :
         (talliedWeek.numDone >= UPPER_BOUND_DONE[level]) ?  1 :
         (talliedWeek.numDone > LOWER_BOUND_DONE[level])  ?  0 :
                                                            -1 ;

if I include a newline after return. Is this expected?

Short answer - yes.

Long answer - this is all to do with the differences between end-of-statement and end-of-line and the significance of the ; in Javascript.

If JS sees a valid statement followed by a new line it uses it as seen (the ; is not needed). This means that

return

is exactly the same as

return;

and your nested ternary is then seen as a (single) new statement:

(!talliedWeek && level  < 4)                     ?  0 :
(!talliedWeek && level >= 4)                     ? -1 :
(talliedWeek.numDone >= UPPER_BOUND_DONE[level]) ?  1 :
(talliedWeek.numDone > LOWER_BOUND_DONE[level])  ?  0 :
                                                   -1 ;

and is executed (without returning anything) and without error - it is still syntactically correct.

For the same reasons, you don’t put new lines after these returns:

return { a:1, b:2 }
return [1, 2, 3, 4]
1 Like