To fix the ESLint Warning "Function declared in a loop contains unsafe references to variable(s)…no-loop-func" with JavaScript, we shoyuld replace loops with forEach
.
For instance, we write
const showHelp = (help) => {
document.getElementById("help").textContent = help;
};
const setupHelp = () => {
const helpText = [
{ id: "email", help: "Your e-mail address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
helpText.forEach((text) => {
document.getElementById(text.id).onfocus = () => {
showHelp(text.help);
};
});
};
to call helpText.foreach
with a callback to set the document.getElementById(text.id).onfocus
to a function that calls showHelp
.
Using forEach
confines toe scope of the functions within the block so we won’t get unexpect results when the onfocus
callback runs.