This is an example from a blog post by Avaylo Gerchev that addresses IIFE's. The following block of code returns 4 repeated 'undefined' responses by design:
function printFruits(fruits){
for (var i = 0; i < fruits.length; i++) {
setTimeout( function(){
console.log( fruits[i] );
}, i * 1000 );
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);
Avaylo then shows how to produce what (to me) would have been the expected output of the first code block (it outputs the values of the array):
function printFruits(fruits){
for (var i = 0; i < fruits.length; i++) {
(function(){
var current = i; // define new variable that will hold the current value of "i"
setTimeout( function(){
console.log( fruits[current] ); // this time the value of "current" will be different for each iteration
}, current * 1000 );
})();
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);
I understand that the IIFE creates a new scope. What I don't understand is the reason why the first block of code doesn't produce the (again, to me) expected output of returning the values in the array. I've been staring at this for a few days now, thus I conclude that my javascript knowledge is missing something fundamental.
Thank you for any insight!