Reputation: 32683
What is difference between
while(condition){
var variable;
...
}
and
while(condition){(function(){
var variable;
...
})();}
Can somebody explain me defference?
Upvotes: 2
Views: 216
Reputation: 1038930
In the first case the variable is accessible anywhere inside the while
(and even after it). In the second case it is private and accessible only inside the auto-invoking anonymous function. So the difference is basically in the scope of the variable. The second example seems pretty convoluted without providing more context.
First example:
while(condition) {
var variable;
... // the variable is accessible here
}
// the variable is accessible here
Second example:
while(condition) {
(function() {
var variable;
... // the variable is accessible here
})();
// the variable is NOT accessible here
}
// the variable is NOT accessible here
Upvotes: 7
Reputation: 47776
The auto calling function basically creates a scope. Variables defined inside it will not be accessible outside the while loop.
var i = 0;
while (i++ == 0) {
var a = "hi a";
}
console.log(a); //hi a
var ii = 0;
while (ii++ == 0) {
(function() {
var b = "hi b";
})();
}
console.log(b); //Uncaught ReferenceError: b is not defined
Upvotes: 1
Reputation: 22770
In the first case, variable
accessible anywhere in the function that encloses the while
. That's because JavaScript does not have a local scope, only function scope.
This might be undesirable in some cases and hence the second variant, which encloses the variable (and loop's body) within anonymous function.
Upvotes: 2
Reputation: 83366
Variables have function scope in JavaScript. So in the first loop variable
is visible anywhere inside your function—the function that contains the while loop, that is.
In the second one, variable
is visible only inside the anonymous function, since that's the function in which it's declared.
Upvotes: 2