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?