Consider the following JavaScript:
for (var i = 0; i < foo.length; i++) {
DoStuff(foo[i]);
}
for (var i = 0; i < bar.length; i++) {
DoStuff(bar[i]);
}
This code seemed fine to me as a developer coming from a C# background. Unfortunately, this code generates a warning with Visual Studio.
Message 1 'i' is already defined
Okay, sure. It is clear what is happening -- the first declaration of i does not confine i's scope to that of the for loop. I could do a couple of things:
for (var i = 0; i < foo.length; i++) {
DoStuff(foo[i]);
}
for (i = 0; i < bar.length; i++) {
DoStuff(bar[i]);
}
I find this solution incorrect due to the fact that the second for loop now has its 'correctness' coupled to that of the first loop -- if I remove the first loop the second loop has to change. Alternatively:
for (var fooIndex = 0; i < foo.length; i++) {
DoStuff(foo[fooIndex]);
}
for (var barIndex = 0; barIndex < bar.length; barIndex++) {
DoStuff(bar[barIndex]);
}
This seems better, and is what I am currently settled on, but I am unhappy with the potentially long names. I make the naming standard of my indices dependent on the variable they are iterating over to guarantee unique name declarations. Unfortunately, If I have a list called "potentialDiagramImages" I don't really want to do:
foreach(var potentialDiagramImagesIndex in potentialDiagramImages){
var foo = potentialDiagramImages[potentialDiagramImagesIndex];
}
This starts to edge on 'too long of a variable name' in my eyes. I don't know if SO agrees with me, though. In addition, the initial problem still exists with this implementation if I have to iterate over the same list twice in the same scope (for whatever reason).
Anyway, I am just curious how others tackle this scoping dilemma.