This is my code:
function func(){
for(i=0; i < 5; i++){
alert('g');
}
}
for(i=0; i < 5; i++){
func();
alert('h');
}
What I expected was: gggghgggghgggghgggghggggh
but what received was just ggggh
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.
This actually doesn’t have to do with function vs. block scope – it has to do with implicit global variables.
The short story: You are accidentally creating a global variable in your
forloop – if you usefor(var i=0;rather thanfor(i=0;you’ll get the expected results.The slightly longer version: