Perhaps I donโt know how the environment index variables for fall into the scope, but I was very surprised when one of my loops did not end, apparently because the function called from the loop contained i for its for loop index.
Here is a little script to demonstrate this behavior:
var loopOne = function(test) { for(i = 0; i < test.length; i++) console.log(getMask(test)); }; var getMask = function(pass) { var s = ""; for (i = 0; i < pass.length; i++) { s = s + "*"; } return s; }; loopOne('hello');
If I run this in Chrome and look at the console log, I should see ***** five times. However, I see it only once. Upon further inspection, if I type i in the javascript Chrome console, it will output 6 ( = 'hello'.length + 1 ). This makes me think that i become part of the global scope and is not limited to the scope of the for loop for which it was necessary.
It is right? If so, what is better for defining the for loop index variable in javascript?
source share