Abraham
Abraham

Reputation: 15730

eslint warning Function declared in a loop contains unsafe references to variable(s) no-loop-func in forEach loop

In my React project, I have a simple .js file with the following code

let oldInfo

function getChanges() {
    const newInfo = {};
    let keys = ["name", "age", "sex"];

    oldInfo = "one";
    for (const key in newInfo) {
        keys.forEach(subkey => {
            if (oldInfo[subkey] === newInfo[key])
                console.log(subkey);
        });
    }
}

getChanges();

And it gives a no-loop-func warning that though I researched a lot, couldn't figure out the risk.

Line 9:22:  Function declared in a loop contains unsafe references to variable(s) 'oldInfo'  no-loop-func

What is the risk? how can I fix this?

Here is the warning on Eslint Demo editor

Upvotes: 2

Views: 2782

Answers (2)

Erman Kadir Kahraman
Erman Kadir Kahraman

Reputation: 719

For avoid this warning (error), you can use for of instead of forEach

let oldInfo;

function getChanges() {
  const newInfo = {};
  let keys = ["name", "age", "sex"];

  oldInfo = "one";
  for (const key in newInfo) {
    for (let subkey of keys) {
      if (oldInfo[subkey] === newInfo[key])
        console.log(subkey);
    }
  }
}

getChanges();

forEach expects a synchronous function.

forEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.

Quote from Array.prototype.forEach() - JavaScript | MDN

You can find good explanation and example on this page.

Upvotes: 0

Hariom Balhara
Hariom Balhara

Reputation: 892

"This error is raised to highlight a piece of code that may not work as you expect it to and could also indicate a misunderstanding of how the language works"

From https://eslint.org/docs/rules/no-loop-func

Also, read https://www.albertgao.xyz/2016/08/25/why-not-making-functions-within-a-loop-in-javascript/

In this particular case, you can fix it by defining the forEach callback function outside getChanges method(e.g. by the name logIteration) and modify forEach callback like this

 keys.forEach(logIteration)

Upvotes: 1

Related Questions