Does the syntax (whitespace) of a javascript function return affect the result? [duplicate]

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:

  1. multiline expression -- fails
  2. expression on single line -- works
  3. wrapping expression in paretheses -- works
  4. setting multiline expression to variable, then returning variable -- works

See working examples: http://jsfiddle.net/drzaus/38DgX/

Can anybody explain why this happens?

Answers:

Answer

This is correct behavior. Putting return; in a function will cause it to return undefined. In your example, the line break after return makes the parser think this is the end of the statement, so it returns undefined.

Answer

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:

return (
  a1 && a2
  ...
  d1 && d2
);

There are more details (and a quote from the spec) at: Trouble understanding semicolon insertion

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.