Closures

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

Closure Definition

A closure is a function and its environment packaged such that it can access its environment even when passed out of its current lexical scope.

...now you need to know what is a lexical scope...

A Simple Example

What does the call to f() result in?

function makeClosure() {
   var x = 10;
   return function() {
      return x+1;
   }
}
var f = makeClosure();
f(); // returns what?
         

Note how x has local scope within the function but is being used outside of the function.

Why should you care?

Closures are handy for:

Not just because it is useful in functional programming and other super geeky things ...

Braing Teaser

What does this output?

var a = [];
for (var i=0; i<10; i++) {
   a.push(function() { return i; });
}
for (var j=0; j<a.length; j++) {
   console.log(a[j]());
}
         

Solution