Uncategorized

Javascript closures and scope are confusing

I hate this about Javascript:


for (var i=0,l=arr.length; i<l; i++) {
  var item = arr[i];
  setTimeout(function () { do_something_with(item) }, 0);
}

That won’t actually do what it looks like it should do.

The problem is that the “item” in this case isn’t actually scoped to that block, and everything is a reference, so what happens is that the item that do_something_with() sees is always the last entry in arr.

In order to create a new closure you have to do it like this:


for (var i=0,l=arr.length; i<l; i++) {
  var item = arr[i];
  setTimeout(function (i) {
    return function () { do_something_with(i) }
    }(item), 0);
}

That calls a function immediately to create a new closure around the item.

I think there are some things coming in Javascript’s future that gets around this. Until then, this has bitten me a bunch of times and is very annoying.

Standard

2 thoughts on “Javascript closures and scope are confusing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s