When Is It Dangerous To Line Break After A Close Parenthesis In Javascript?
Solution 1:
When you're trying to return an object,
return {
'foo': 'bar'
}
will return the object, whereas
return
{
'foo': 'bar'
}
will return undefined
. Javascript will automatically insert a semicolon after return
in the second example, and the object will never be reached.
For functions, because function()
isn't valid on its own, it shouldn't make a difference if the brace is on the same line or the next.
See also section 7.9.1 Rules of Automatic Semicolon Insertion of the ECMAScript specification. Aside from return
, there are four other situations where a semicolon will be inserted due to a newline: break
, continue
, throw
and ++
or --
.
When a
continue
,break
,return
, orthrow
token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after thecontinue
,break
,return
, orthrow
token.
Solution 2:
A semicolon will be inserted only if the following line is not a valid continuation of the previous line (see exceptions below). So function() {
with {
on the next line is always safe.
From the ECMAScript spec:
When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
• The offending token is separated from the previous token by at least one LineTerminator.
• The offending token is }.
Exceptions to this rule are the increment/decrement operators, continue
, break
, return
and throw
, whose arguments must always be on the same line:
When a ++ or -- token is encountered where the parser would treat it as a postfix operator, and at least one LineTerminator occurred between the preceding token and the ++ or -- token, then a semicolon is automatically inserted before the ++ or -- token.
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
Solution 3:
It is safe.
I took a quick look at the semicolon insertion rules in the spec (3rd edition), and for function declarations it is OK.
Post a Comment for "When Is It Dangerous To Line Break After A Close Parenthesis In Javascript?"