Skip to content Skip to sidebar Skip to footer

What Is The Benefit Of Assigning A Self Executing Anonymous Function To A Variable In Javascript?

I was reading a post about how to fire a function after a window resize was complete and came across some examples that assigned self executing anonymous functions to variables: va

Solution 1:

The main reason for this is namespacing variables. Functions introduce a new variable scope. In the case of the above example, timer is not clobbering the global namespace while still being available to the code that needs it.


Since I apparently need to clarify:

The goal is to have a variable outside the function:

var timer;

function delay() {
   // use timer
}

Because if the variable would be inside the function, it would be reinitialized every time. We want a persistent value outside the function though.

In the above code timer is a global variable though. We don't want that. To avoid that, we close the variable up in a new scope so it's accessible to the delay function, but not globally:

var delay = (function () {
    var timer;

    returnfunction () {
        // use timer
    };
})();

delay is now a function just as before which can use timer outside itself, yet timer is not in the global scope.

Post a Comment for "What Is The Benefit Of Assigning A Self Executing Anonymous Function To A Variable In Javascript?"