News for hackers. Stuff that matters.
Re:JavaScript Interview Question by kenjackson on Thursday January 20, 2011 @01:37PM (#2124705)
Does this work (from a non-JS person -- I like reading JS books, but don't code in it at all). This is certainly less elegant, but seems easier to follow:

  var els = document.getElementsByTagName('li');

  for(i=0; i < els.length; i++){
    var j = i;
    els[j].addEventListener('click', function(){alert(j);}, false);
  }
Re:JavaScript Interview Question by lhorie on Thursday January 20, 2011 @01:56PM (#2124791)
No, it doesn't because j is in the same scope as i.

Your confusion is because of a javascript quirk

  for (...) {
    var foo = bar
  }
is actually the same as

  var foo
  for (...) {
    foo = bar
  }
Notice how you only ever have one foo

What you need is:

  for (...) {
    (function(bar) {
       var foo = bar
    })(bar)
  }
which create a new foo every time you loop
Re:JavaScript Interview Question by buerkle on Thursday January 20, 2011 @01:45PM (#2124744)
That doesn't work. Variables in javascript are not block scoped but function scoped.
Re:JavaScript Interview Question by kenjackson on Thursday January 20, 2011 @01:52PM (#2124774)
Thanks. Good to know.