Beware of JavaScript semicolon insertion

One of most tricky behaviors by JavaScript interpreters is semicolon insertion.

Why semicolon insertion?

Unfortunately, semicolons are optional in JavaScript, which leads to developers being sloppy, using them in some places, while omitting them elsewhere. “Luckily”, JavaScript interpreters take this into account, and at runtime, insert semicolons where it thinks it should be one.

Good and bad code style examples

So, how is this a problem? Let’s start by taking a look at the below code:

// Good
return {
	javascript : "fantastic"
// Bad!
	javascript : "fantastic"

The problem

So, I’m sure some of you wonder what the hell’s wrong with having the opening curly bracket on a new line? You love that coding style and it all becomes clearer. The answer is semicolon insertion. The bad code is interpreted like this:

return; // Semicolon inserted, believing the statement has finished. Returns undefined
{ // Considered to be an anonymous block, doing nothing
	javascript : "fantastic"
};// Semicolon interpreted as an empty dummy line and moved down

My advice

Since it does matter where you put the curly brackets, my strong recommendation is to use the opening one at the end of the line, preceded by other code. Also, make sure to always put semicolons in your code, to avoid potential problems.


I first saw this lovely example being presented by Douglas Crockford at @media Ajax 2007 (my report), and my pal Remy presented it in his blog. I just wanted to re-iterate the point here, since a lot of people doesn’t seem to know about semicolon insertion.

Posted in Developing,JavaScript,Technology |

Leave a Reply

Your email address will not be published. Required fields are marked *