Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

Javascript and I Need Some Closure

JSLint Keeps Warning Me About Calling a Function Within A Loop

I use JSlint to check my JavaScript on a regular bases, most of the time it just for light scripts that I just need to check to make sure that I don't have a typo. But occasionally I check more robust scripts and I find myself presented with an error message that says "Problem at line XXX character XX: Be careful when making functions within a loop. Consider putting the function in a closure".

I know I've come across this in the past and I know that I fixed it, but the problem is I can never remember what the heck I did to fix it. Then I remembered that I have a blog! I can just put it there and never have to search far for the answer ever again!

Here's the problem:

function myHappyFunction() {
   var a = document.getElementsByTagName('a');
   for(var i = 0; i <= a.length - 1; i++) {
      a[i].onclick = function(e) {
         alert('Ouch!');
      };
   }
}

I'm not 100% sure what the problem is, but I know it has something to do with the fact that the assigning the function in this way, it acts as if it is a local variable. Since we are attaching it to another local variable inside our main function, the "called" function may not exist at runtime. Or something like that. Truthfully, I really don't understand it. I just know that it's bad practice and it causes memory leaks or something horrible sounding.

So how do we fix it? It's simple really. Just add a return call inside the attached function, like so:

function myHappyFunction() {
   var a = document.getElementsByTagName('a');
   for(var i = 0; i <= a.length - 1; i++) {
      a[i].onclick = function(e) {
         return function() {
            alert('Ouch!');
         };
      }(i);
   }
}

JSLint is happy, I'm happy and it seems that we finally have some closure. I hope this helps anyone else trying to figure this out, but to be honest I'm doing this more for me than for you. I'm kind of selfish like that sometimes. Enjoy and let me know if any of you have any insight into this "closure" thing. Thanks.

[EDIT - 9/19/09] I had some bad typos in my example. "getElementsByTagname" should be "getElementsByTagName". The "a" array was not indexed with the "i" variable. And the array length was not correct in the for-loop. The examples have been updated properly.