0

I've an warning that "Don't make functions within a loop", I know there are already some post regarding this Don't make functions within a loop

But I'm newbie and has no idea how to do this, can anyone help?

for (const el of testing) {
  el.addEventListener("click", function() {
    const apple = this.dataset.open;
    document.getElementById(apple).classList.add(orange);
  });
}

1 Answers1

3

in fact when you do

for (const el of testing) {
  el.addEventListener("click", function() {
    const apple = this.dataset.open;
    document.getElementById(apple).classList.add(orange);
  });
}

you create a new instance of a new function each time the loop is iterate

a better way is to have a function declared outside the loop

function myfunction() {
    const apple = this.dataset.open;
    document.getElementById(apple).classList.add(orange);
  });

for (const el of testing) {
  el.addEventListener("click", myfunction);
}
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35