I understand that IIFE is an anonymous function which invokes it self, but I'm pretty curious to know, where this is used. Can any one please explain one quick use case?
(function() {
console.log('IIFE!');
})();
I understand that IIFE is an anonymous function which invokes it self, but I'm pretty curious to know, where this is used. Can any one please explain one quick use case?
(function() {
console.log('IIFE!');
})();
It's a great way to create a container for things; a new, contained scope. I use them around all of my JavaScript in a page, for instance:
(function() {
var x;
function foo() {
}
})();
Without the IIFE, if I just had this at the topmost scope of a normal script:
var x;
function foo() {
}
...then x
and foo
would be globals, and the global namespace is already way overcrowded. By putting them inside a function, I keep them contained. They can refer to each other, they're common to my code inside that IIFE, but they're not globals.
It doesn't just have to be for all of the code on a page, either; I use this for privacy at multiple levels. For instance, if I want to create something with one external symbol but a number of internal pieces:
var externalFoo = (function() {
var someVariable;
function foo() {
}
function bar() {
}
return foo;
})();
That creates one symbol in the outer context (which may or may not be global, depending on where the codeblock above is), externalFoo
. Inside the IIFE, I have a number of private things that presumably help externalFoo
do its job, but they're "plumbing" that shouldn't be accessible from outside.
For me, this is the primary use for them, creating privacy for their contents.
Some people use IIFEs to create new scopes for closures in loops, like this:
var i;
for (i = 0; i < 10; ++i) {
(function(index) {
setTimeout(function() {
doSomthingWith(index);
}, index * 100);
})(i);
}
That's so that the doSomethingWith
sees each value (0, 1, 2, ...). For that use case, though, I prefer not to create and destroy the outer anonymous function (the IIFE) on each loop iteration (instead using a single builder function), and I prefer to be clearer about what I'm doing:
var i;
for (i = 0; i < 10; ++i) {
setTimeout(buildHandler(i), i * 100);
}
function buildHandler(index) {
return function() {
doSomthingWith(index);
};
}