I was checking out the code of has.js and was puzzled by the initial semicolon here:
;(function(g){ // code }()(this);
As far as I know, it does absolutely nothing. It does not put the function in expression position as ()
or !
do: (function(){}())
or !function(){}()
. It seems to be merely a line ender for an empty line.
What is the purpose of this semicolon? An OCD desire for symmetry between the beginning and end of the IIFE? :)
Using semicolons allows you to write multiple statements on the same line. But this is bad practice. You should never write statements on the same line (unless required). If you use semicolons, there is a chance you get this bad habit.
An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.
It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts: The first is the anonymous function with lexical scope enclosed within the Grouping Operator () . This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
It's there to prevent any previous code from executing your code as the arguments to a function.
i.e.
mybrokenfunction = function(){ } //no semicolon here (function(g){ })(this);
will execute mybrokenfunction with your anonymous function as its argument:
mybrokenfunction = function(){}(function(g){})(this);
If you could guarantee that there won't be an unterminated (no semicolon) function before yours, you could omit the starting semicolon, but you can't, so it's just safer to put that extra semicolon in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With