Recently, my coworker and I engaged in a discussion about the best and worst practices when it comes to using the var keyword within loops. Here is my approach:
for (var i = 0; i < anArray.length; i++) {
for (var j = 0; j < anotherArray.length; j++) {
var a1 = someValue1;
var a2 = someValue2;
var a3 = someValue3;
var a4 = someValue4;
var a5 = someValue5;
...... //Additional processes involving a1-5
}
}
I opted to utilize var inside nested for loops. Let's say loop i
iterates 2000 times and j
does so 3000 times. However, my colleague contends that this practice of using var in these loops can lead to memory leaks and must be avoided. Is this claim accurate?
He insists that "vars should be declared outside the loop to ensure they are bound by function scope and will be disposed of once the scope concludes." Is there truth to this statement?
Aside from concerns about memory leaks, is this method considered poor practice, and if so, why?
I am hesitant to agree as I believe that, even when vars are used within a loop, a1-5 will still be disposed of at the end of the function.