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.
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]()); // 3If 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.
As 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.
In fact I would argue it's important that if the candidate shows practical knowledge of ES6 you need to make sure they also grasp the actual semantics (i.e. they won't rely on implementation details of Babel and run into errors in native ES6 environments).
That said, if you are hiring for a dedicated frontend developer role, the majority of JS you write will have a build step. If it has a build step, you should use modern tooling. If you use modern tooling, you might as well include Babel to make the developers' lives less of a pain.