Tag: closure

Fun with JavaScript Closures + Scoping

by Warlock on Jul.10, 2010, under Javascript

It’s easy to forget that variable scoping in JavaScript is at the function level and not a the block level like what you get with C/C++/C#/Java/etc. This can have some counter intuitive implications when you’re dealing with closures. Consider the following example:

var closure;

for(var i = 0; i <= 5; i++) {
  var x = i * i;
  if( i == 1 ) {
    closure = function() { alert(x); };
  }
}

closure();

What do you think the output of the alert box will be? At first blush it's easy to think it will be 1 because the variable x is declared within the for loop.

Run Code

In reality, though, the output is 25 because despite the variable declaration in the for loop, the code is functionally equivalent to this:

var closure;
var x;

for(var i = 0; i <= 5; i++) {
  x = i * i;
  if( i == 1 ) {
    closure = function() { alert(x); };
  }
}

closure();

This is important to remember when working with closures in loops.

So how do solve this problem? Manually create a new scope by creating and invoking an anonymous function.

var closure;

for(var i = 0; i <= 5; i++) {
  var x = i * i;
  if( i == 1 ) {
    (function(x) {
      closure = function() { alert(x); };
    })(x);
  }
}

closure();

Run Code

With the newly introduce lexical scope, the program returns 1 as one would expect.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...