0

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?

Aditi
  • 1,188
  • 2
  • 16
  • 44
  • _"only a single instance of the function is defined"_ - That's not true... The output is wrong/as it is because of the scope of variables defined with `var` – Andreas Aug 22 '18 at 14:14

1 Answers1

0

Using a local variable will do the trick.

var funs = [];
for (var i = 0; i < 13; i++) {
  let localIndex = i;
  funs[i] = function() { // Non-Compliant
    return localIndex;
  };
}
print(funs[0]()); // 0
print(funs[1]()); // 1
print(funs[2]()); // 2
print(funs[3]()); // 3
Grégory
  • 338
  • 2
  • 10