by mathgeek · 10y ago · 0 comments
Opinions will differ, but IMHO closure is a great concept to divide those who know JS at a conceptual level (or at least have crammed for the interview) from those who don't.
What I also like about it is that a closure isn't the only way to solve it. You can use `let` for example to make sure the variables are block scoped, or use `bind` to partially apply a function with the number.
So in the end it's a conceptually very simple exercise that can give you a very good insight into how much the candidate knows about how JS actually works.
const f = (k) => {
const funcs = [];
for(let i = 0; i < k; i++) {
funcs.push(() => i);
}
return funcs;
}
const test = f(4);
console.log(test[0]()); // 0
console.log(test[1]()); // 1
console.log(test[2]()); // 2
console.log(test[3]()); // 3 // 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]()); // 3As an interviewer I can see why you would want to force someone to jump through arbitrary hoops like that but if someone can show me `() => i` and explain why that works, that would be good enough for me.