News for hackers. Stuff that matters.
Re:JavaScript Interview Question by dmvaldman on Thursday January 20, 2011 @12:43PM (#2124448)
Spoiler Alert!

each list item alerts 4 when clicked. This has to do with closures in js. The way I understood it (and please correct if inaccurate) is that each list item has an event listener that calls function: alert(i). However, it's not true that each list item has its own value for i. The value of i is figured out only when the link is clicked.

Once script finishes, i has the value 4, and when clicked on, each list item draws from this value of i instead of the one in which it is originally assigned.

Re:JavaScript Interview Question by bcrescimanno on Thursday January 20, 2011 @12:49PM (#2124486)
"The value of i is figured out only when the link is clicked."

This makes it sound a bit like magic. A more accurate description is that the usage of the variable "i" within the closure is simply a reference to i in the outer function--not a copy of the value.

A great follow-up is to describe the memory implications of what they've done here and how memory use can be improved.

Re:JavaScript Interview Question by dmvaldman on Thursday January 20, 2011 @01:08PM (#2124580)
ahh thank you this makes more sense. If I understand you correctly...

- each list item has a pointer to a function: alert(i) (functions are first class objects)

- the value of i is determined from the outer function (which is in some unraveled way the for(i=0; i<els.length; i++)) because it is within the scope of the above function

-link item executes alert(i) with i = 4, when clicked.

Re:JavaScript Interview Question by broquaint on Thursday January 20, 2011 @12:55PM (#2124521)
The behaviour is due to the fact that variables in JavaScript are scoped to the function, although as that code is in the global scope and lacks a var declaration it will live under the global object (window in this case). So in that example each closure captures the same variable hence 4 being produced within each alert(). For more info see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/C...