Variable scope in for loops

The following two lines are fine with applab (no warnings):
for (var i = 0; i < 4; i++) { }
for (var i = 0; i < 4; i++) { }
However, if those same two lines are placed within a function definition, the second will result in a warning that variable i is already defined.
function foo() {
for (var i = 0; i < 4; i++) { }
for (var i = 0; i < 4; i++) { } // Warning on this line!
}
I’ve had a couple of students ask me about this. I’ve done a little online research and I understand that JS doesn’t support block-level scope (or at least doesn’t without using “let”), but I don’t understand why one gets a warning and one doesn’t. Any advice?
Thanks!
Alex

Hey @alex.jacoby I’ve checked in with our engineering team and we believe it’s just a bug in the way that we’re checking the code. We’ve logged the issue so that we can eventually get it fixed. Thanks for reporting it!

After running into this problem and doing more research, I think the issue is related to JavaScript’s lack of block level scope after all. Creating a loop counter variable (like i) inside a for loop’s header, JavaScript hoists the variable scope up to the function level, so you can’t declare i again in a subsequent for loop. You can use the existing variable, though, so for the second for loop, you could use for(i = 0; i < …) and it works (at least in App Lab).

1 Like