Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediate functions JavaScript

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?

like image 477
dublintech Avatar asked Nov 13 '12 16:11

dublintech


2 Answers

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"
like image 162
SReject Avatar answered Oct 12 '22 02:10

SReject


Having your days variable in the function scope is exactly the point that example is making. Without the immediately-invoked function, all the variables (days, msg) would be global variables, and will pollute the global namespace.

like image 39
lanzz Avatar answered Oct 12 '22 02:10

lanzz