In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
First you must visit MDN IIFE , Now some points about this
Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.
I am a great fan :) of it because:
Enormously – (Why you should say its good?)
More here.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something
gets used by the function assigned to a
. something
could have some varying value (for loop) and every time a has a new function.
It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.
For example, as mentioned in a comment by Alexander:
(function() {
var foo = 3;
console.log(foo);
})();
console.log(foo);
This will first log 3
and then throw an error on the next console.log
because foo
is not defined.