2

I wanted to solve this question posted as a public question on testdome. Each as[i] should be a function that does alert(i). The code to be bug-fixed is this:

function registerHandlers() {
  var as = document.getElementsByTagName('a');
  for (i = as.length; i-- >= 0;) {
    as[i].onclick = function() {
      alert(i);
      return false;
    }
  }
}

The solution I attempted is this:

function registerHandlers() {
  var as = document.getElementsByTagName('a');
  //made the loop variables more explicit
  for (i = as.length-1; i >=0; i--) {
    var x = i;
    as[x].onclick = function() {
      alert(x);
      return false;
    }
  }
}

I though that variable i is persistent, so I kept its copy in variable x, and use variable x instead of i. But it does not solve the problem completely. Please let me know what is my misunderstanding.

DurgaDatta
  • 3,952
  • 4
  • 27
  • 34

1 Answers1

9

Your i and x values are declared in exactly the same scope, so by the time the function is executed x will be its final value. You could create a closure like this:

function registerHandlers() {
    var links = document.getElementsByTagName('a');

    for (var i = 0, len = links.length; i < len; i += 1) {
        links[i].onclick = generateHandler(i);
    }

    function generateHandler (index) {
        return function () {
            alert(index);
            return false;
        }
    }
}
Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • Thanks, it works. Is it necessary that we write function outside of loop? We still make some minimal modification so as to have the function defined inside the loop? – DurgaDatta May 10 '15 at 15:09
  • NP. There's lots of reasons not to make functions in a loop - its definitely a good practice to follow and doesn't have any downsides. It usually adds to readability, as you can see from my example above. [Here](https://jslinterrors.com/dont-make-functions-within-a-loop) is a good article with some of the reasoning. – Alex McMillan May 10 '15 at 15:13
  • hey guys...I know its a couple of years later..but since the link in Alex's comment isnt working, I recommend seeing this guys video for showing why not to use functions in a loop - https://www.youtube.com/watch?v=Nqfs14iu_us – Marvel Moe Aug 19 '17 at 02:59