I have some javascript code that resembles this:
for (i = 0; i < numTimes; i++) {
DoStuff();
}
function DoStuff() {
for (i = 0; i < 100; i++) {
console.log(i);
}
}
I am finding that the second time the DoStuff()
is called, the value of i
in the loop starts with 1. I assume this is due to the way the scoping of variables work in JS. Other than changing the variable name in the DoStuff()
function, what's the cleanest way of resolving this and can someone explain this behavior?
EDIT: Thanks for the responses. It appears that JS has "lexical scope" instead of "block scope". Is this what I am seeing here? Can someone explain what lexical scope is in newbie terms?