69 lines
2.4 KiB
Plaintext
69 lines
2.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Defining functions inside loops in JavaScript can lead to several issues and is generally considered bad practice. The main problems associated with this approach are related to performance, scope, and potential unintended behavior:
|
|
|
|
* When a function is defined inside a loop, the function is re-created on each iteration of the loop. This can cause unnecessary overhead and lead to performance issues, especially if the loop runs repeatedly. Defining the function outside the loop is more efficient so that it is created only once.
|
|
* Functions defined inside loops have access to the loop's variables and parameters. This can sometimes lead to unintended behavior or bugs due to closures. Closures in JavaScript capture the environment in which they are created, including variables and parameters, and this can cause unexpected results when those variables change during the loop.
|
|
* Code that defines functions inside loops can be harder to read and maintain, especially for other developers who might not expect functions to be redefined within the loop. Keeping functions separate and clearly defined is better, improving code organization and understandability.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
for (let i = 0; i < 5; i++) {
|
|
function processItem(item) { // Noncompliant: Function 'processItem' inside a for loop
|
|
// Some processing logic
|
|
console.log(item);
|
|
}
|
|
|
|
processItem(i);
|
|
}
|
|
----
|
|
|
|
Define the function outside the loop and use the function parameters to pass any needed variables instead.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function processItem(item) {
|
|
// Some processing logic
|
|
console.log(item);
|
|
}
|
|
|
|
for (let i = 0; i < 5; i++) {
|
|
processItem(i);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures[Closures]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Scope[Scope]
|
|
|
|
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[]
|