News for hackers. Stuff that matters.
Re:JavaScript Interview Question by mustpax on Thursday January 20, 2011 @12:44PM (#2124454)
Just adding var wouldn't be enough, you're still referencing the variable from the outer scope. You need to create your own copy. Instead of:

    els[i].addEventListener('click', function(){alert(i);});
Do:

    els[i].addEventListener('click',
        function() {
            var j = i;
            alert(j);
        });
Edit: This is wrong, archgoon has the correct answer below. That'll teach me for jumping on closure problems in the morning :)
Re:JavaScript Interview Question by archgoon on Thursday January 20, 2011 @01:05PM (#2124563)
That won't work either. You're still setting the variable to the global variable i. The only way I can think of doing this is as follows

els[i].addEventListener('click',function(k){function(){alert(k)}}(i));

EDIT: See lhorie's suggestion below for a much cleaner way of doing this. http://news.ycombinator.com/item?id=2124532

Re:JavaScript Interview Question by theoretical on Thursday January 20, 2011 @12:57PM (#2124528)
That won't quite work, as you're still just copying the value of i when that function is executed, which will be 4.

You could make the function take a parameter, then return a function which uses that parameter, or use currying.

Edit: I've posted a working version in my comment further down, http://news.ycombinator.com/item?id=2124559

Re:JavaScript Interview Question by mumrah on Thursday January 20, 2011 @01:47PM (#2124753)
I create a closure outside of the event registration: http://pastebin.com/igzWkgKF
Re:JavaScript Interview Question by SMrF on Thursday January 20, 2011 @12:54PM (#2124516)
I think you want var j = i outside the function.

Edit: Oops, this is wrong as well. :-)

Re:JavaScript Interview Question by tremendo on Thursday January 20, 2011 @12:56PM (#2124523)
alert('"'+i+'"')