
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
52 lines
1.1 KiB
Plaintext
52 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Defining a function inside of a loop can yield unexpected results. Such a function keeps references to the variables which are defined in outer scopes. All function instances created inside the loop therefore see the same values for these variables, which is probably not expected.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
var funs = [];
|
|
for (var i = 0; i < 13; i++) {
|
|
funs[i] = function() { // Non-Compliant
|
|
return i;
|
|
};
|
|
}
|
|
console.log(funs[0]()); // 13 instead of 0
|
|
console.log(funs[1]()); // 13 instead of 1
|
|
console.log(funs[2]()); // 13 instead of 2
|
|
console.log(funs[3]()); // 13 instead of 3
|
|
...
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Make sure this function is not called after the loop completes.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
primary location: function declaration
|
|
|
|
secondary: loop
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 23 Mar 2020, 18:57:47 Elena Vilchik wrote:
|
|
legacy key FunctionDefinitionInsideLoop
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|