Search code examples
javascriptself-invoking-function

Is there ever a reason to use a named self-invoking function?


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?


Solution

  • 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);