What is the purpose of a semicolon before an IIFE? [duplicate]

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? 🙂

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.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Where is "vue.config.js" file?

Similar Posts