Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
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);
  });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!