Does the syntax (whitespace) of a javascript funct

2019-01-15 19:41发布

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:

  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?

3条回答
Summer. ? 凉城
2楼-- · 2019-01-15 20:17

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.

查看更多
欢心
3楼-- · 2019-01-15 20:18

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.

查看更多
Luminary・发光体
4楼-- · 2019-01-15 20:33

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

查看更多
登录 后发表回答