"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.
var
) Not sure I get what you're asking... – Strikedays
will be in the function scope, not the global. That's the scope advantage. – Farthingale