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