Yianna Kokalas

Javascript Automatic Semicolon Insertion

09 Jun 2016

Ecma and JS

The title uses the common term of javascript but we’re going to be going into behavior that is implied by ecma ISO standards. So when ecma is discussed we’re articulating the expected behavior that the javascript interpreter in your browser must adhere to.

Automatic Semicolon Insertion otherwise known as ASI

This is a behavior designed for automatically terminating lines of code. Here are some examples of when your code will work with ASI and otherwise fail.

// Fail with no ASI
{ 0 1 }
{ 0 1 } 2

This is not valid ecma grammar and is not transformed by ASI. The reason why this is not transformed by ASI is because there is no use of a new line terminator. In order to insert a semicolon the token parser must run into an offending token separated by a newline otherwise it will throw an error. Uncaught SyntaxError: Unexpected number(…)

// not valid ecma but ASI does work because of newlines
{ 0
1 } 2

// produces a valid ecma sentence
{ 0
;1 ;} 2;

In this case 1 would be the offending element but since we separated it with a newline then it is preceded with a semicolon. Next the right curly brace } is considered an offending token so that too gets preceded with a semicolon. Lastly, 2 actually does not get preceded with a semicolon. This is because the parser has hit the end of what’s called an input stream of tokens.

// fail
for (foo; bar
)

This is what’s called a for statement and the closure of paranthesis is consider it’s head (). Inside it’s head it requires the use of a semi colon for statements. ASI will never insert one of the two semicolons in the header of a for statement

return
'foo' + 'bar'

// becomes

return;
'foo' + 'bar';

Keep in mind in the above example that return won’t return the value of 'foo' + 'bar' since a newline after it’s call will result in a semi colon.

thing = 'foo'

// becomes

thing = 'foo';
// fail
if (20 > 14)
else c = 'foobar'

this is not a valid ecma sentence and the asi will not alter it by placing a semicolon before the else token. As you can see this can be a lot to remember but becomes good habit after a while. Hope this clears up some confusion of when to use semi colons in your javascript and when not to. However, it is recommended to always add semicolons to end your statements; it will avoid side effects.

Tweet me @yonk_nyc if you like this post.

Tweet