0

I'm currently learning javascript from the following book 'JavaScript: The Good Parts - O'Reilly Media', which says the following:

It is important to understand that the inner function has access to the actual variables of the outer functions and not copies in order to avoid the following problem:

// BAD EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the
wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the
node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes) 
{
    var i;
    for (i = 0; i < nodes.length; i += 1) 
    {
        nodes[i].onclick = function (e) 
        {
            alert(i);
        };
    }
};
// END BAD EXAMPLE

Question: I don't understand what the problem is, if someone could give me a clear example with numbers and results that would greatly be appreciated.

fYre
  • 1,212
  • 3
  • 11
  • 16
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Antti Haapala -- Слава Україні Aug 03 '13 at 16:45
  • No matter which node you click on, it will alert the same value, equal to the number of nodes you passed in. See also http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function and http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – DCoder Aug 03 '13 at 16:46
  • @AnttiHaapala nice! the same dupe, cv'd a few seconds after you, without having seen your vote. – John Dvorak Aug 03 '13 at 16:47
  • @user2628157, you might want to read existing questions and answers, I found the answer to your question in a few seconds by searching for "javascript closure in loop". – Antti Haapala -- Слава Україні Aug 03 '13 at 16:54

2 Answers2

2

The value of i changes every time the loop is incremented, and the event handlers will alert whatever the current value of i is. So if there are 8 elements, all of them will pop-up a value of 7 when the loop is done running.

The point of the example is that many people assume that when each handler is initially bound with the current value of i (e.g. 0, 1, 2, etc.) that it then doesn't change as i is incremented. This example demonstrates that this isn't the case, and that the event handler functions always have access to the current value of i, even after being bound.

Shaun
  • 2,446
  • 19
  • 33
0

The issue here is that the function you pass to onclick keeps a reference to the same i that is incremented at each loop turn. Thus, when the click is triggered, i has been incremented to match the number of elements.

axelcdv
  • 753
  • 6
  • 18