Semicolon before self-invoking function?
Self-invoking functions are surrounded by parentheses, and in JavaScript parentheses are overloaded to mean
- Grouping expressions to override precedence:
(x + y) * z
- Function application :
f()
Putting a semicolon before the function prevents the function from becoming an argument to whatever precedes it when the parentheses become confused with function application.
Consider
var x = 42
(function () { ... })()
is the same as
var x = 42(function () { ... })()
but
var x = 42
;
(function () { ... })()
is the same as
var x = 42;
(function () { ... })()
I write all JavaScript in a semicolon-free style. When writing without semicolons at the end of every line, due to Automatic Semicolon Insertion (ASI), there are a few special cases that can "be confusing" at first:
Starting a top-level expression with an operator, a
(
(open parenthesis) in this case, which like most other operators, can continue the previous expression and thus suppresses the "automatic insertion of a semicolon". (This generally only occurs when using a self invoking function.)Just kidding about #2: there isn't one! (Learn only one rule and you too can enjoy life without extra semicolons ;-)
Since I write in a semicolon-free style I thus always write it as (where the function-expression can naturally span multiple lines):
;(FunctionExpression)()
In my case it isn't about "safety" or trying to "catch an error" (honestly, if your style is to use semi-colons and you forget a semi-colon, then you've already created the error elsewhere and writing a ;
at the start for "safety" is hogwash). No; in my case it is done for consistency with knowledge of my chosen style and "knowing" that starting a line with an operator can continue an expression from a previous line.
See JavaScript: Semicolon Insertion (Everything You Need To Know) for the details (it is by far the best article I have seen on the subject).
Happy coding.
If you concatenate two files with self-invoking functions together that look like this:
File A:
(function(){...A...})()
File B:
(function(){...B...})()
File A+B:
(function(){...A...})()(function(){...B...})()
You have two statements without separator. This happens when you cat files together and then minify them.
Now the author of file B puts a semicolon in front:
File B2:
;(function(){...B2...})()
And you'll get a working script:
(function(){...A...})();(function(){...B2...})()