JS loop variable scope

2020-08-01 05:14发布

问题:

I was trying out some simple JS code. I was aware that we should use var keyword to declare a loop variable inside the loop say for loop to avoid global variable declaration. However I realized that the loop variable exists after the execution of the loop too:

var a = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < a.length; i++)
    document.write(a[i]); //123456
document.write(i);  //6

This is not inline (in fact it does not need to be, I know) with how loop variable of for loop in Object Oriented concepts behaves. I know I should not try to compare the JavaScript with in OO language for any aspect. However I am just guessing that the behavior in OO languages is better.

I think, if we put this code in directly in <script> tag then it actually adds the loop variable to global scope which is not desired. Is it like that? or I am thinking it wrong way?

We can achieve such behavior by creating explicit function scope:

var a1 = [1, 2, 3, 4, 5, 6];
(function () {
    for (var i1 = 0; i1 < a.length; i1++)
        document.write(a[i1]); //123456
})();

document.write(i1);  //undefined

But is it the standard way / followed in production? What other things can be done?

回答1:

We can achieve such behavior by creating explicit function scope. But is it the standard way / followed in production?

Yes. Functions are the only possibility to introduce a new scope in JavaScript (though that might change in future versions with let); and IIFEs are heavily used in production as well.

What other things can be done?

To limit the scope of i to the for-loop's block? None (let alone let). However, you hardly will need to do that, since nothing will interfere with it - var i is still scoped local to your function. Sometimes, you even might want to use i after the loop as an ongoing counter.



回答2:

JavaScript has only function scope any variable defined using var in side function is available inside function only. for loop does not create any scope for variables.



回答3:

Javascript is a bit strange and has, IMHO, a lot of defects that make it a poor language for middle/big projects.

"var" mean that the variable is only available in the current function scope: All variables are defined at the begening, before the function is run and set to "undefined". So:

alert(i);
var i=4;
alert(i);
var i=5;
alert(i);

internally mean:

var i=undefined;
alert(i);
i=4;
alert(i);
i=5;
alert(i);

In Structured programming, all code should be in functions, so that mean that your "var" keyword will work as expected. But if you write code in the global scope, "var" has no real sense.