This is my code:
function func(){
for(i=0; i < 5; i++){
alert('B');
}
}
for(i=0; i < 5; i++){
func();
alert('A');
}
What I expected was: BBBBBABBBBBABBBBBABBBBBABBBBBA
but what received was just BBBBBA
I found out that’s because there is function scope, not block scope in JS. What I’d like to know is how to preserve such a behavior. I mean to force something like block scope. Otherwise it’s very easy to make really nasty bugs – e.g. while using a function somebody else wrote or the one you wrote yourself, but a few months earlier.
Make sure you use
var i=0instead of justi=0. Otherwise, it floats into the global scope and gets used by both loops.