I'm also in the process of interviewing for a front-end engineer position, so thank you for replying and providing feedback.
I'm assuming it has to be written this way because the function being pushed was referencing i, which was within the scope of the closure. Turning it into an IIFE breaks out of that. Thoughts?
// Assuming pre-ES6
function iterate(k) {
var funcs = [];
for(var i = 0; i < k; i++) {
(function(num) {
funcs.push(function() {
return num;
});
})(i);
}
return funcs;
}
var itTest = iterate(4);
console.log(itTest[0]()); // 0
console.log(itTest[1]()); // 1
console.log(itTest[2]()); // 2
console.log(itTest[3]()); // 3