Immediate functions JavaScript
Asked Answered
H

8

15

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?

Herstein answered 13/11, 2012 at 16:11 Comment(4)
and you won't see that vars from the outsideBehoof
If it wasn't inside the closure above it would be a global variable. (the scope would be window, ie, the same as declaring it without var) Not sure I get what you're asking...Strike
No, as you said days will be in the function scope, not the global. That's the scope advantage.Farthingale
IMHO you're interpreting his comment the wrong way. It's not so much that there are advantages to your code (although there are, but that's not the point). The main reason is that other pieces of Javascript on the same site will have an additional layer of protection against any goofs you may have made.Stunt
E
19

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"
Elsworth answered 13/11, 2012 at 16:15 Comment(1)
I think this is best answer. It is not a case immediate enclosing function versus normal enclosing function. It is immediate function versus no enclosing function at all. Just vanilla JavaScript.Herstein
A
7

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.

Antinode answered 13/11, 2012 at 16:15 Comment(0)
M
6

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.

Moonset answered 13/11, 2012 at 16:14 Comment(3)
What? How would days be in the global scope if it is defined using var inside the function?Bohunk
Try to re-read my answer. Without the immediately-invoked function, the variables would be global.Moonset
@Moonset Uggh, sorry I read too fast. My mistake! I thought you were implying that without the immediate invocation, everything inside the function would be in the global scope. Reading-comprehension fail.Bohunk
D
1

"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.

Disario answered 3/2, 2014 at 14:46 Comment(0)
L
0

The idea behind var being inside the function is

not to leak any variables to the global scope

The thing is that in this case days will not be visible outside the function and if you will try to write in console console.log(days) you will get days is not defined

This is done because you never know who else will be using your code later and may be he will redefine your variable days.

Liner answered 13/11, 2012 at 16:16 Comment(0)
B
0

days is still in the local scope of the function. What you're doing here is performing a task inside a local scope so that anything you define inside that scope doesn't pollute the global namespace. Otherwise you would have the following in the global scope:

var days = ['Sun','Mon'];
// ...
// ...
alert(msg);
Bohunk answered 13/11, 2012 at 16:16 Comment(0)
R
0

In JavaScript, local variables have function scope, not block scope. For example, in the code you posted, days is in fact local to the function:

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

But if you were to say the following, in global scope:

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

days would become a global variable (visible to everything in the outer scope), even though it is defined inside a block. Does that make sense?

Renayrenckens answered 13/11, 2012 at 16:17 Comment(0)
F
0

i got the same question
i thought the only benefit of the immediate function is it should be used with the anonymous function
when we use a anonymous function ,it means it will never be reused ;without a name how could you invoke it?
so make it as an immediate function be better .
the author didn‘t make it clear !

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

the days is also in the local scope of func ,not a global variable

Flashcube answered 26/5, 2014 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.