Mirgorod
Mirgorod

Reputation: 32683

What's the difference in this while loop?

What is difference between

while(condition){
    var variable;   
    ...
}

and

while(condition){(function(){
    var variable;   
    ...
})();}

Can somebody explain me defference?

Upvotes: 2

Views: 216

Answers (5)

Darin Dimitrov
Darin Dimitrov

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

Alex Turpin
Alex Turpin

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

http://jsfiddle.net/

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

Got closures to consider as well as Darin Dimitrov comments.

Upvotes: -2

Xion
Xion

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

Adam Rackis
Adam Rackis

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

Related Questions