Is there ever a reason to use a named self invoking function?
For example:
(function foo()
{
alert('Hello World! Named Self Invoking Function Here');
})();
As far as my learning has taken me, this acts the same as an anonymous self invoking function, with no extra advantages (you can't call it again following the invokation), and no extra disadvantages as it does not "pollute" the global scope (I think).
Are there any times when it would make sense to name a self invoking function like the above?
A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console.
Self-Invoking FunctionsFunction expressions can be made "self-invoking". A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.
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.
JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”. The code inside a function is executed when the function is invoked.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.
If you needed a recursive self-invoking function then it may make sense:
(function loop(i) {
console.log(i);
i++;
if(i < 10) {
loop(i);
}
})(0);
I use this pattern for polling data from servers periodically. This makes the code less clutter (especially setTimeout
line).
(function poll() {
$.get("/somedata", function (data) {
// Processing data...
setTimeout(poll, 1000);
});
})();
It would be useful for recursion, but you should avoid named function expressions for the time being. They are not supported correctly in Internet Explorer until version 9.
See: http://javascript.info/tutorial/functions-declarations-and-expressions
"IE<9 doesn’t support NFE"
Naming self-invoked functions can increase readability. For example in the case that you are creating several closures via self-invoked functions, by providing names it increases code readability at no harm (other than losing old-IE support, as noted.) In essence, you are creating named code blocks, which can be a nice way to break up a large function.
e.g.,
function bigFunction() {
(function doTheFirstThing() {
//code here.
})();
(function doTheSecondThing() {
//code here.
})();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With