Friday, June 7, 2013

Why use semicolons in JavaScript

I always use semicolons even though they are optional in JavaScript. A key reason for me is convention and javascript minification (although closure compiler will rewrite your js with semicolons inserted). But if you want to know what else could go wrong even if you do not do minification there is actually only one case. When a line starts with `(` it should have a semicolon before it.

An Example

When you have an immediately executed function to create a new scope:

// define a function with assignment
var fn = function () {
   //...
} // semicolon missing at this line

// then execute some code inside a new scope
(function () {
    //...
})();

Will get interpreted as :

var fn = function () {
    //...
}(function () {
    //...
})();

The second function will fail with a "... is not a function" error at runtime.

Another example 

// careful: will break
a = b + c
(d + e).print()
// Will get interpreted as:
a = b + c(d + e).print();

Alternate Solution

 A potential solution if you want to be a cowboy and not use semicolons everywhere is to use a semicolon before ‘(‘:

; (d + e).print()

Its also potentially a good idea when your file starts with '(' since if someone (who does not use semicolons) does concatenation of your file it might become a problem. 

An example was from this answer: http://stackoverflow.com/a/1169596/390330

No comments:

Post a Comment