JavaScript Closures

for 6 year olds

Darren DeRidder / @73rhodes

"If you can't explain it to a six year old, you don't really understand it." - Richard Feynman








What's a closure?

"Closures are functions that refer to independent (free) variables." [MDN]

Why Closures?

  • Common in JavaScript.
  • Node.JS callbacks.
  • Some practical uses.
  • Some unexpected problems.

The Simplest Closure


 
    var x = 1;
    function foo() {
      return x;
    }
 
                    

The Traveller

A man goes on a long trip. Before leaving, he takes a snapshot of his house.

While he's away, the house is replaced with a condo. The man is unaware and continues to show the photo and describe his house to the people he meets.

The Traveller code example


 
    var color = 'white';

    function leaveHome () {
       // a variable in leaveHome's scope
       var description = "My house is " + color;
       // returns another function, creating a closure over description
       return function() {
          console.log(description);
       }
    }

    var travellingMan = leaveHome();
    travellingMan(); // "My house is white"
    color = 'red';   // They painted the house
    travellingMan(); // "My house is white"
 
                    

Things to Notice

  1. In Javascript, functions are objects, too.
  2. Functions can create and return other functions.
  3. Functions can be anonymous.
  4. The returned function "closes over" the variables in the scope where it was created, forming a closure.

More examples

  • An "inner function" is a closure.
  • Functions that get returned are closures.
  • Functions that get passed (ie. callbacks) are closures.
  • Any function that accesses variables outside it's immediate lexical scope is a closure.

Related Methods

  • Function.call
  • Function.apply
  • Function.bind

Thanks!

http://darrenderidder.github.io/talks/Closures