I have a simple function which has another function inside its for loop. The main function returns the sub function. When the main function is called, the loop runs but the sub function is not yet executed since it is not yet called. The sub function is called after the loop has been executed and hence the value of i points to the value of the last element of the array. If I want this to have a new binding to each of the values in the array, how do I fix it?
function getName() {
const arr = ['a', 'b', 'c', 'd'];
for (let i = 0; i < arr.length; i++) {
function sendName() {
alert(arr[i]);
}
}
return sendName;
}
var receiveName = getName();
receiveName();
getName()which returns a function to be called later. How can that single call have "a new binding to each of the values"? It's a single result fromgetName(). Maybe you could return an array of functions?sendNamevariable you return does not exist. Which is part of your larger problem: YourgetName()returns only a single function. How would you even call different functions which point to different indices (which is the part that actually already works due to your usage ofletin the loop).