This question already has an answer here:
In writing a javascript function to evaluate a multi-variate condition, I came across what seems like a parser error in Javascript. Please let me know if I'm forgetting something, or if this is appropriate behavior.
In my function, I'm returning the AND
result of several variables, like so:
return
// a comment, for kicks
a1 && a2
&&
b1 && b2
&&
// another comment
c1 && c2
&&
d1 && d2
;
However, even when all of those variables have an explicit value of true
, the function is returning undefined
instead of the expected true
.
I've tried several variations of returning this expression, and I've found:
- multiline expression -- fails
- expression on single line -- works
- wrapping expression in paretheses -- works
- setting multiline expression to variable, then returning variable -- works
See working examples: http://jsfiddle.net/drzaus/38DgX/
Can anybody explain why this happens?
This is correct behavior. Putting
return;
in a function will cause it to returnundefined
. In your example, the line break afterreturn
makes the parser think this is the end of the statement, so it returnsundefined
.Aha -- hooray for related links: JavaScript Whitespace Syntax Error
It appears that the parser sees a newline after
return
and automatically treats it to a semicolon. In the cases where it works, there's either a parethesis indicating to the parser that it's actually a multiline clause, or it's on a single line (thus negating the autoinsert), or in the case of a variable it's treated differently by the parser.What you're running into is an odd behavior in Javascript known as "semicolon insertion". To make a long story short, when the end of a line can be interpreted as the end of a statement without introducing a syntax error, Javascript will do so. The newline after your
return
statement qualifies -- to prevent this from happening, you could wrap the returned value in parentheses, like so:There are more details (and a quote from the spec) at: Trouble understanding semicolon insertion