var x = "hello " var my_closure = function (y) { alert(x + y); } my_closure("world"); #### for (@some_array) { # Declaring this in the loop creates a new variable per # instance of the loop. my $x = $_; push @closures, sub { # Do something using x. I'll just return it. return $x; }; } # We now have one closure per array element. #### for (var i = 0; i < some_array.length; i++) { // Declaring this in the loop creates a one variable for // all instances of the loop. var x = some_array[i]; closures.push(function () { // Do something using x. I'll just return it. return x; }); } // All closures now point at the last element. #### for (var i = 0; i < some_array.length; i++) { // This declares and immediately calls a function, and x // is scoped to that function call. (function (x) { closures.push(function () { // Do something using x. I'll just return it. return x; }); )(some_array[i]); // And here is where we bind the value. } // We now have one closure per array element.