15

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?

Nealbo
  • 529
  • 4
  • 20
  • 1
    It's a named function expression, so any reasons for using named function expressions apply. – Felix Kling Jun 08 '12 at 10:37
  • 3
    The canonical example is recursion: `(function fib(n){ return n<=2?n-1:fib(n-1)+fib(n-2); })(7)` – davin Jun 08 '12 at 10:38
  • Maybe because the code inside makes use of the function name? – MaxArt Jun 08 '12 at 10:38
  • (related) http://stackoverflow.com/questions/8585279/do-you-name-your-anonymous-function-in-a-function-expression – Felix Kling Jun 08 '12 at 10:41
  • Here's a slightly convoluted example that may help when debugging: http://jsfiddle.net/AC5eu/. The call stack currently says `b - (anonymous function)`; if you give it a name it would say `b - a` or something similar. – pimvdb Jun 08 '12 at 10:43
  • @pimvdb - So in other words, it could help with tracking down a problem? – Jared Farrish Jun 08 '12 at 10:45
  • possible duplicate of [How does naming an anonymous function in JavaScript make a difference?](http://stackoverflow.com/questions/10318890/how-does-naming-an-anonymous-function-in-javascript-make-a-difference) -- whether self invoking or not does not make a difference. – Felix Kling Jun 08 '12 at 10:45
  • @Jared Farrish: Yes, it could make finding the source clearer. But in Chrome you can also just click the call stack entry to jump to the function anyway, so it's not extremely helpful. – pimvdb Jun 08 '12 at 10:47
  • @pimvdb - Ok, thanks. I prefer using named functions, for (my own) readability, so I would probably want to know why you would *not* want to name your functions... `:P` – Jared Farrish Jun 08 '12 at 10:48
  • related: [Using Named Immediately-Invoked Function Expression (IIFE) instead of comments](http://stackoverflow.com/q/15530374/1048572) and [What is the practical use of an IIFE with a name?](http://stackoverflow.com/q/18365801/1048572) – Bergi Oct 20 '14 at 15:37

6 Answers6

14

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);
whostolemyhat
  • 3,107
  • 4
  • 34
  • 50
10

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);
  });
})();
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
nonowarn
  • 620
  • 8
  • 18
3

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"

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • It doesn't say "not supported", it says "not implemented correctly". If you know the quirks and know that it doesn't really affect you (which is mostly the case), you can still use them without crashing IE. Must-read on the topic: http://kangax.github.io/nfe/#jscript-bugs – Bergi Jan 21 '14 at 02:18
  • @Bergi: I didn't say "not supported", I said "not supported correctly". If you want to split hears, here is of course a difference between supported and implemented, but that it's not implemented correctly has the effect that it's not supported correctly. – Guffa Jan 21 '14 at 10:10
  • My English phrasing is too bad for splitting hears anyway, sorry :-/ But I didn't mean what you said, but that quote you gave. – Bergi Jan 21 '14 at 12:25
  • @Guffa once you've said "not supported" it ends there. Not supported is not supported. Nothing you try to add to it, will ever apply to its definite meaning. It's the same as if you've written return at the first line of your function body. :) All browsers have some level of misunderstanding at this point. The keyword function is a hoister just like var declaration is. So..., you do the thinking. – Bekim Bacaj Nov 06 '16 at 00:05
1

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.
   })(); 
}
B Robster
  • 40,605
  • 21
  • 89
  • 122
  • IEFEs seem to be overkill for that. Use them only if you *need* the closures (for scoping/garbage collection), for anything else comments (and maybe [blocks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block)) will suffice. – Bergi Jan 21 '14 at 02:22
  • 1
    @Ben Roberts Ever heard of JavaScript Labels? – Bekim Bacaj Nov 06 '16 at 00:16
0

You can use it for initialization, the line of code that you have to run first and then it will call another script.

Moonhint
  • 11
  • 1
0

It provide us with a way to create recursive, self-executing functions. In the following demo, I've created a self-executing function that increments a counter, logs it, and then calls itself recursively:

var counter = 0;
// Create a self-executing function block; however, rather
// than passing in an anonymous, headless function, let's
// pass in a named function.
(function useCounter() {
  // Increment and log counter.
  console.log(++counter);
  // Call *this* function again in after a short timeout.
  setTimeout(useCounter, 1000);
})(); // Self-execute.

Another more common use of self-invoking functions is data privacy, everything wrapped in them is only available within the scope of these functions.

For more details visit https://en.wikibooks.org/wiki/JavaScript/Anonymous_functions

Murtaza Hussain
  • 3,851
  • 24
  • 30