Does javascript function syntax (space) return result function?

When writing a javascript function to evaluate a multivariate condition, I came across what looks like a parser error in Javascript. Please let me know if I forgot something or if this is appropriate behavior.

In my function, I return the AND result of several variables, for example:

 return // a comment, for kicks a1 && a2 && b1 && b2 && // another comment c1 && c2 && d1 && d2 ; 

However, even if all of these variables have an explicit true value, the function returns undefined instead of the expected true .

I tried several return options for this expression, and I found:

  • multi-line expression <
  • expression on one line - works
  • expression for packaging in paretheses - works
  • setting a multi-line expression to a variable, then returning the variable - works

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

Can someone explain why this is happening?

+4
source share
3 answers

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

+6
source

What you work for is weird behavior in Javascript known as "insert semicolon". In short, when the end of a line can be interpreted as the end of a statement without introducing a syntax error, Javascript will do this. A new line after your return is suitable to prevent this, you can wrap the return value in parentheses, for example:

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

More information (and a quote from the specification) can be found at Troubleshooting semicolons

+7
source

Yeah - cheers for related links: JavaScript syntax error Whitespace

It looks like the parser sees a new line after return and automatically processes it with a semicolon. In cases where it works, there is either a parethsis indicating to the parser that it is actually a multi-line sentence, either on a single line (thus negating autoinsert), or in the case of a variable that it processed differently with parser.

+2
source

All Articles