Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference in this while loop?

Tags:

javascript

What is difference between

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

and

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

Can somebody explain me defference?

like image 452
Mirgorod Avatar asked Aug 03 '26 14:08

Mirgorod


2 Answers

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
like image 104
Darin Dimitrov Avatar answered Aug 06 '26 02:08

Darin Dimitrov


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.

like image 28
Adam Rackis Avatar answered Aug 06 '26 02:08

Adam Rackis