0

I would like to pass an argument to a callback function inside a for loop. The problem is the callback is called after the for loop ends and then the parameter does not exist anymore.

See the following code snippet:

function foo(x){
    console.log(x)
}
for(var i = 0; i < arr.length; i++) {
    var myObj = customObject()
    myObj.on('click', function(){
        foo(arr[i])
    }
}

myObj is clicked on after the for loop ends which triggers an error:

TypeError: arr[i] is undefined

Is there any way to force the argument to be passed by its value at time of binding the callback function?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Erhan
  • 157
  • 4
  • 16

1 Answers1

1

Try an IIFE:

myObj.on('click', function() {
    (e => foo(e))(arr[i]);
});

The problem was that the click event was firing after the whole loop had finished - so i was arr.length, had not passed the conditional statement in the loop, and as such arr[i] was undefined.

You'd also need to use let instead:

for (let i = 0; i < arr.length; i++) {
    let myObj = createObject();
    myObj.on("click", function() {
        (e => foo(e))(arr[i]);
    });
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 3
    The whole goal behind duplicates on Stack Overflow is to keep the quality answers to the same question at one place. This question has been asked many times before, it has a great explanation, you have a dupe hammer to singlehandedly mark it as duplicate, yet you choose to answer it with no more info than can be found in the dupe target... It's not my down vote but I can imagine this could be the reason. – Ivar Jun 22 '19 at 22:05