What is difference between
while(condition){
var variable;
...
}
and
while(condition){(function(){
var variable;
...
})();}
Can somebody explain me defference?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With