I'm aware of the fact that JavaScript doesn't have finer grained scopes than "global" or "per-function". But is there any real problem with writing something like:
function test() {
for (var i = 10; i < 20; i++) { /* ... */ }
for (var i = 03; i < 04; i++) { /* ... */ }
}
It's annoying to have to keep coming up with new names for indexing variables (which is what I've been doing: fooIndex
, barIndex
, etc.) And moving the declarations to the top of the function isn't great either:
function test() {
var i;
for (i = 10; i < 20; i++) { /* ... */ }
for (i = 03; i < 04; i++) { /* ... */ }
}
Then if your uses are far away from the declaration, you might forget to delete unused variables. Or you might accidentally write into global scope because you thought you had var-declared something you didn't.
It seems a lesser evil to put the var on anything you intend to be local. Is it? According to this answer redefining it as var more than once has no effect, but that situation is more contrived than loop variables. Is there a truly good reason not to do things like the first case above?