What are the rules for JavaScript's automatic semicolon insertion (ASI)? -
well, first should ask if browser dependent.
i've read if invalid token found, section of code valid until invalid token, semicolon inserted before token if preceded line break.
however, common example cited bugs caused semicolon insertion is:
return _a+b;
which doesn't seem follow rule, since _a valid token. on other hand, breaking call chains works expected:
$('#mybutton') .click(function(){alert("hello!")});
does have more in-depth description of rules?
first of should know statements affected automatic semicolon insertion (also known asi brevity):
- empty statement
var
statement- expression statement
do-while
statementcontinue
statementbreak
statementreturn
statementthrow
statement
the concrete rules of asi, described in specification:
three cases described:
when token (
lineterminator
or}
) encountered not allowed grammar, semicolon inserted before if:- the token separated previous token @ least 1
lineterminator
. - the token
}
e.g.:
{ 1 2 } 3 // transformed { 1 ;2 ;} 3;
the
numericliteral
1
meets first condition, following token line terminator.2
meets second condition, following token}
.- the token separated previous token @ least 1
when end of input stream of tokens encountered , parser unable parse input token stream single complete program, semicolon automatically inserted @ end of input stream.
e.g.:
a = b ++c // transformed to: = b; ++c;
this case occurs when token allowed production of grammar, production restricted production, semicolon automatically inserted before restricted token.
restricted productions:
updateexpression : lefthandsideexpression [no lineterminator here] ++ lefthandsideexpression [no lineterminator here] -- continuestatement : continue ; continue [no lineterminator here] labelidentifier ; breakstatement : break ; break [no lineterminator here] labelidentifier ; returnstatement : return ; return [no lineterminator here] expression ; throwstatement : throw [no lineterminator here] expression ; arrowfunction : arrowparameters [no lineterminator here] => concisebody yieldexpression : yield [no lineterminator here] * assignmentexpression yield [no lineterminator here] assignmentexpression
the classic example, returnstatement
:
return "something"; // transformed return; "something";
Comments
Post a Comment