Explaining a closure can be tough but people can memorize the answer from a book. This question tests if they actually understand it.
This questions asks the candidate to write some code to console.log the index of a <li>
in a <ul>
.
<ul>
<li></li>
<li></li>
<li></li>
...
</ul>
There's maybe a way of doing this with event delegation but generally I'll see candidates doing this:
var list = document.querySelectorAll('li');
for (var i = 0; i < list.length; i++) {
list[i].addEventListener('click', function (e) {
console.log(i);
});
}
The above won't work and will instead always console.log list.length
. This is becuase i is updated in the loop. The way to solve this is:
var list = document.querySelectorAll('li');
var cb = function (i) {
return function () {
console.log(i);
};
};
for (var i = 0; i < list.length; i++) {
list[i].addEventListener('click', cb(i));
}
- When they select the
<li>
's ask them what they have (the answer is a NodeList). - If they get to the above (they might need some help) then ask them why that works and the original way they did it (if they did the first incorrect answer) didn't work.