Sunday, November 24, 2013

Semicolons are good for you!

Everyone knows (well almost everyone, my wife probably doesn't) that semicolons in Javascript are not necessary and I had a "pleasure" of maintaining Javascript file where most of the semicolons where missing. Programmer was relying on automatic semicolon insertion and had no idea what kind of problems this might cause. The script was working fine however relying on automatic insertion is dangerous and might lead to not-so-easy to find bugs. One example I can think of involves self-invoking functions. See the code below:

var drinkBeer = function () {
// gulp..gulp..gulp..
}

(function () {

})();

At the first glance there is nothing wrong with the code above. However when it runs the self invoking function will be passed as an argument to drinkBeer function declared above. Then drinkBeer will be invoked causing script to fail. As far as interpreter is concerned the code will look something like:

var drinkBeer = function () {
// gulp..gulp..gulp..
}(function () {

})();

..and BOOM!  The problem can be easily fixed by inserting semicolon in the right place. This code below will make interpreter happy, you happy and your boss and will sure put you in place (or maybe not) for big promotion:

var drinkBeer = function () {
// gulp..gulp..gulp..
};

(function () {

})();

No comments:

Post a Comment