Javascript infamous Loop issue? [duplicate]

I’ve got the following code snippet.

function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function () {
            alert(i);
        };
        document.body.appendChild(link);
    }
}

The above code is for generating 5 links and binding each link with an alert event to show the current link id. But It doesn’t work. When you click the generated links they all say “link 5”.

But the following code snippet works as our expectation.

function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function (num) {
            return function () {
                alert(num);
            };
        }(i);
        document.body.appendChild(link);
    }
}

The above 2 snippets are quoted from here. As the author’s explanation seems the closure makes the magic.

But how it works and How closure makes it work are all beyond my understanding. Why the first one doesn’t work while the second one works? Can anyone give a detailed explanation about the magic?

5 Answers
5

Leave a Comment