Live data from Hacker News

JavaScript Interview Question

cam.ly

11–20 of 63 posts

Re: JavaScript Interview Question

#11
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

#13

I think they all alert '3' because of the missing 'var' keyword.

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

#14
post #4
post #2

Is it poor etiquette to state what i think the answer is?

Please do.

It won't alert quite what you want - when you click on each element in the list, it will alert "4".

This is because the function assigned to the click event of each li is bound to the "i" variable used in the loop by a closure. Variable i is incremented to 4 before the loop ends, so that is what each will print.

You could use make the function used in the click handler take a parameter, then use partial function application (or currying) to fix the value of the parameter.

Re: JavaScript Interview Question

#19

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…

"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

#20
post #4
post #2

Is it poor etiquette to state what i think the answer is?

Please do.

Wrap the line of code inside the loop inside another function, which will have the effect of binding the iterator i to the desired value before the event handler anonymous function is created.
Post reply on HN