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

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.

Leave a Comment