Avoiding variable declaration inside a loop

JavaScript is a language with a dynamic garbage collection. Memory allocated even if inaccessible, will not be given free before the garbage collector deallocates it.

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory. While this might be acceptable for variables of scalar data types, it may allocate a lot of memory for SCFile variables, or huge arrays or objects.

Unrecommended implementation

The following implementation, in which a variable is declared inside a loop, is not recommended.

var arr = new Array();
arr = [ "IM10001", "IM10002", "IM10003", "IM10004" ];
for(i=0;i<arr.length;i++)
{
var file = new SCFile("probsummary");
file.doSelect('name="'+arr[i]+'"');
// do something with file
}

Recommended implementation

The following implementation, in which a variable is declared before a loop, is recommended.

var arr = new Array();
arr = [ "IM10001", "IM10002", "IM10003", "IM10004" ];
var file = new SCFile("probsummary");
for(i=0;i<arr.length;i++)
{
file.doSelect('name="'+arr[i]+'"');
// do something with file
}