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

216
Views
Basic JS Question, Arrow Function with a callback using parameters in addEventListener

I have a basic function here. I want to be able to pass parameters into it. However, it is being called by the addEventListener. Now, after reading on here and researching I got it to work so that if I put the TOP option in - it works. When I use the bottom option, just below it -it does not work. (Not if I want to use parameters). I just am wondering a basic explanation as to why the arrow function with a callback can take parameters, how is this going round exactly? Not sure I am explaining my question well.

for (i = 0; i < dots.length; i++) {
  dots[i].addEventListener('click', (e) => imgChoose(e, i));
}

for (i = 0; i < dots.length; i++) {
  dots[i].addEventListener('click', imgChoose);
}

var i = 0;

function imgChoose(e, i) {
  var test = dots[i].className;
  console.log(e);
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

It's got nothing to do with arrow functions specifically, you can use normal functions too. What matters is that when addEventListener calls your function, it will pass in exactly one parameter: the event. If you want to then call a function with two parameters you can, but you must write that code yourself.

Here's how it would look with a regular function:

dots[i].addEventListener('click', function (e) { imgChoose(e, i) });

P.S.: as written, you have a single variable i which is being used for all the click callbacks. So they're all going to use the final value of i, which will be equal to dots.length. You should create i in the initialization of your loop, and make sure to use let, not var.

for (let i = 0; i < dots.length; i++) {
about 4 years ago · Santiago Gelvez 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!