Defining a function inside of a loops can yield unexpected results because under the covers, only a single instance of the function is defined. Rather than creating new function instances, the loop iterations simply update the function's variables. Instead, the function should be returned.
Noncompliant Code Example
var funs = [];
for (var i = 0; i < 13; i++) {
funs[i] = function() { // Non-Compliant
return i;
};
}
print(funs[0]()); // 13 instead of 0
print(funs[1]()); // 13 instead of 1
print(funs[2]()); // 13 instead of 2
print(funs[3]()); // 13 instead of 3
...
I've been thinking but can't figure out the compliant solution. What should it be?