Skip to content

Instantly share code, notes, and snippets.

@rattlion
Created January 8, 2016 19:36
Show Gist options
  • Save rattlion/467ed4e7a5d8e8fc7aca to your computer and use it in GitHub Desktop.
Save rattlion/467ed4e7a5d8e8fc7aca to your computer and use it in GitHub Desktop.

Question

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>

Answer

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment