
Creating an Immediately Invoked Function Expression in JavaScript
An Immediately Invoked Function Expression (IIFE) will execute immediately without needing to be called.
A common use for an IIFE is to prevent polluting the outer scope. Variables declared inside the IIFE are not accesable outside of that IIFE.
// this function will be immediately invoked
;(function(){
var x = "inside an IIFE!";
alert(x);
})();
// referencing x outside of the IIFE above will result in an error because x is not defined.
alert(x);
By wrapping the function in parenthesis, the parser knows to interpret it as a function expression and not a function declaration.