Wednesday, 16 September 2015

Automatic Semicolon Insertion

I've been recommending to people that they not rely on Automatic Semicolon Insertion for years now, and frankly wish that the strict variant had removed it. Just wanted to share the best argument for putting semicolons where they belong that I've seen in a long time:

var foo = {
    a: "ay",
    b: "bee"
}

(function() {
    console.log("Hi there");
})();

That blows up, because the opening ( in the inline-invoked function expression at the end is interpreted as the opening parentheses of a function call, with the {...} being what it tries to call. Since that's not a function, it fails with TypeError: (intermediate value)(intermediate value) is not a function.

As the lady said: Ain't nobody got time for that! Use your semicolons.

4 comments:

William said...

Very good point.

Pat Migliaccio said...

I know this was written a couple years back, but just to point out the fact that this is a reason why writing IIFE's as ;(function () { })(); prefixed with a semicolon is best practice.

Unknown said...

@Pat - A leading ; is best practice in scripts that may be combined, but I've never seen anyone call doing it before all IIFEs "best practice."

Best practice in my view is put semicolons where they belong.

Angel17 said...

I find this post so informative. Thanks for sharing this one! vacation property management Siesta Key, FL