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?
for
loops at once. But when there is REALLY complex code that we've to write its hard to spot thei
within that 'spaghetti' code.