Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I move the function outside the loop

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);
  });
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading