23

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? :)

mwcz
  • 8,949
  • 10
  • 42
  • 63

1 Answers1

47

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.

deadbeef404
  • 623
  • 4
  • 14
Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
  • 3
    Mostly used for defense against web tools which concatenate JavaScript files. – Stephen W. Wright Apr 17 '18 at 19:45
  • 4
    I answered this originally in 2013 and I should point out now that most modern javascript web tools are smart enough to handle this now, and with ES2015 and newer, there's better encapsulation, leading to less IIFEs. I haven't had to use an IIFE in years. – Erty Seidohl Apr 17 '18 at 20:03