Please bear with me, I could only explain the problem in the comments of the cod
ID: 647005 • Letter: P
Question
Please bear with me, I could only explain the problem in the comments of the code snippet below. Please read through them carefully. Question at the end:
I usually tend to name the variables used in for loops with i, like this:
for (var i = 0; i < arr.length; i++){
// do some COMPLEX operations here
}
This looks fairly simple; but when I'm at it I may require nested for loops within the above for loop. So, introducing the complexity now:
for (var i = 0; i < arr.length; i++) {
// do some
// VERY
// COMPLEX
// operations
// here
for (var i = 0; i < javascript_object.list.length; i++) {
// I may have inadvertently forgot of the variable 'i' was been used earlier
for (var j = 0; j < javascript_object.list[i].another_list.length; j++) {
// Perform more complex operations here
}
}
this.getReports(arr[i]) // the value of this i
// which I now think refer to the first for loop might have been changed
// in second for loop and may lead to dangerous results!
}
How to avoid this from happening? How could the variables be named carefully so that it wouldn't clash with other variables being declared elsewhere?
Explanation / Answer
One common approach, which is also used in the code you posted is to simply to use the next letter in the alphabet, so:
for(var i = 0; i < length; i++) {
for(var j = 0; j < length; j++) {
for(var k = 0; k < length; k++) {
// More loops?
}
}
}
This approach is lazy, but it works. However, I find that it can get confusing when you're not looping the same array or accessing a multi-dimensional array. In that case, a better approach might be to simply provide more meaningful names:
for(var nameIndex = 0; nameIndex < names.length; i++) {
for(var classroomIndex = 0; classroomIndex < classrooms.length; classroomIndex++) {
// And so forth
}
}
Of course this may be a little wordy for you, but I figure better a little wordy than completely uncomprehensible code. You were probably hoping for a neat hack here to be able to keep the i variable in its own scope. There may even exist a way to do so, however I don't believe in that kind of solution to a problem like this for two reasons:
Nested loops should generally be discouraged anyway. You cannot apply a best practice in a situation in which you're not following a best practice. Call a method instead.
It would leave the next programmer scratching his head wondering why you did it that way, and it is difficult to justify such a decrease in readability just to account for name clashing.
I hope that helps!