Immediate functions JavaScript

dublintech picture dublintech · Nov 13, 2012 · Viewed 9.6k times · Source

Stoyan Stefanov says in JavasScript Patterns that: "you need an immediated function to wrap all your code in its local scope and not to leak any variables to the global scope" page 70.

Here is his example

(function() {
    var days = ['Sun','Mon'];
    // ...
    // ...
    alert(msg);
}());

But surely because days is defined as a var, it will just be functional scope? The only benefit of the immediate function is the function is invoked immediately. There is no scope advantage. Corrcet?

Answer

SReject picture SReject · Nov 13, 2012

It's not about an immediately executed function vs. a regular function; in fact it has very little to nothing in relation.

The sole purpose of an immediately invoked wrapping-function is to scope variables local to the wrapping function.

(function() {
    // This variable is only available within this function's scope
    var thisIsTemp = "a";

    // ...
}());

console.log(thisIsTemp); // undefined        

vs:

// This variable is available globally
var thisIsTemp = "a";

// ...

console.log(thisIsTemp); // "a"