4 ms·
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 t
by danyim 10y ago
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
- mathgeek 10y agoI'd probably ask you to do the printouts from within the function itself. If you haven't already read them, I highly recommend the You Don't Know JS series of books. One of them covers this exact question.
- weaksauce 10y agoneat series of books. thanks for the tip https://github.com/getify/You-Dont-Know-JS https://github.com/getify/You-Dont-Know-JS
- ehsanu1 10y agoIf you can figure that out during an interview, you're solid on the question. That's the gist of it, and knowing that you can use `let` to make it work is good too.
- ricardobeat 10y agoYup, that's what I was thinking of. As others have mentioned, if you can show this, and explain why `let` solves it too, you're good to go.