Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 257
mwcz Avatar asked Jul 31 '13 19:07

mwcz


People also ask

What is the purpose of semi colons (;) in JavaScript?

Using semicolons allows you to write multiple statements on the same line. But this is bad practice. You should never write statements on the same line (unless required). If you use semicolons, there is a chance you get this bad habit.

What is the point of IIFE?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

What is IIFE format?

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts: The first is the anonymous function with lexical scope enclosed within the Grouping Operator () . This prevents accessing variables within the IIFE idiom as well as polluting the global scope.


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 103
Erty Seidohl Avatar answered Oct 25 '22 14:10

Erty Seidohl