Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIFE causing function evaluation [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? :)

like image 786
mwcz Avatar asked Nov 23 '22 05:11

mwcz


1 Answers

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.

like image 198
Erty Seidohl Avatar answered May 18 '23 14:05

Erty Seidohl