High level concepts to remember

  1. Functions can refer to variables defined in outer scopes.
  2. Closures can outlive the function that creates them.
  3. Closures internally store references to their outer variables, and can both read and update their stored variables.

Example #1

1 function sandwichMaker(magicIngredient) { 
2    return function(filling) { 
3      return magicIngredient + " and " + filling; 
4    }; 
5 }

Example #2

 1 function box() { 
 2    var val = undefined; 
 3    return { 
 4       set: function(newVal) { 
 5          val = newVal; 
 6       }, 
 7       get: function() { 
 8          return val; 
 9       }, 
10       type: function() { 
11          return typeof val; 
12       } 
13    }; 
14 } 
15 
16 var b = box(); 
17 b.type(); // "undefined" 
18 b.set(98.6); 
19 b.get(); // 98.6 
20 b.type(); // "number"

This example produces an object containing three closures, its set, get, and type properties. Each of these closures shares access to the val variable. The set closure updates the value of val, and subsequently calling get and type sees the results of the update.