Immediate functions JavaScript

"you need an immediate function to wrap all your code in its local scope and not to leak any variables to the global scope"

This is not true. (Or at least it is debatable)

I think what the OP was asking is, "Do you need an immediate function to create local scope or can you just use normal function scope?" I agree with the OP that a function AND an immediate function will hide the variable days in its own scope. To test if a variable is global, (in the console) you can check if it is defined on window.

Immediate Function:

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

Normal function:

var func = function() {
    var days = ['Sun','Mon'];
    // ...
    // ...
    alert(msg);
};
window.days; // undefined
Object.prototype.toString.call(window.func); // "[object Function]"

As you can see, days is not a global in both cases. It is hidden or private within the function scope. However, I did create a global, func in the second example. But this proves that you do not need an immediate function to create local scope.

PS: I've never read this book. I'm sure the author is smart and knows what they are talking about, but was just not specific enough in this exact case. Or maybe we need more context surrounding the quote to completely understand it.


Technically that is correct (there is no scoping benefit because the function is immediate; a plain boring function would also do that), but don't forget that

  1. you have some code you want to run right now
  2. you don't want that code to leak names into the current scope

So, the function is created because of #2 but it is also invoked immediately because of #1.


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"

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.