domenica 7 aprile 2013

Should you use semicolons in JavaScript?

There has been a quite a bit of chatter recently on whether or not you should use semicolons in your JavaScript code.

JavaScript provides a feature called Automatic Semicolon Insertion (ASI). For the most part there are rarely problems in omitting semicolons, but there are a few cases where semicolons are required to prevent syntax errors or resolve code ambiguities.


A site that triggered a lot of chatter was aresemicolonsnecessaryinjavascript.com which boldly states ‘NO’. The author is really trying to explain we should not just include semicolons everywhere due a fear that our code might break in some environments or parsers (such as JavaScript minifiers). Others are also continuing the same point that we should better understand why semicolons in JavaScript are optional.

Douglas Crockford, a leading expert in JavaScript recommends using semicolons at the end of every simple statement and his ubiqitious JavaScript code quality tool, JSLint, by default expects semicolons to be inserted. A poll on Stack Overflow strongly recommends using semicolons everywhere.

Lastly, I found Armin Ronacher’s post on dealing with JavaScript’s automatic semicolon insertion to be most useful. In particular his summary where he writes:
Are Semicolons Necessary in Javascript? Despite popular belief the answer is "sometimes" and not "no". But to save yourself time and troubles, just place them all the time. Not only will it save yourself some headaches, your code will also look more consistent. Because there will be situations where a semicolon becomes necessary to resolve ambiguities.
So what will I be doing? My vote goes to following Douglas Crockford’s JavaScript coding guidelines for now and I’ll be happily including semicolons in my code.

If you are interested, there are also a couple of discussions on Reddit regarding these couple of posts; Dealing with JavaScript’s automatic semicolon insertion and Are semicolons necessary in JavaScript?.

This entry was posted in JavaScript and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

Nessun commento:

Posta un commento