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

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.