Introduction to Closures

Lesson

Exercises

function makeAccount(initial) {
            var balance = initial;
          
            return function(amount) {
              if (balance - amount >= 0) {
                balance = balance - amount;
                return "Here’s your money: $" + amount;
              }
              return "Insufficient funds.";
            };
          }
          

Basic Requirements

  1. Let's make a counter using closures. For our purposes, a counter is simply a function that, when invoked, returns a number that is one higher than it used to be. For example, this is the behavior that we want:

    counter(); // => 1
              counter(); // => 2
              counter(); // => 3
              

    We could implement this using the global scope like this:

    var count = 0;
              
              function counter() {
                count = count + 1;
                return count;
              }
              

    But now that we know about closures, we can do something way cooler. Finish the implementation of makeCounter below so that we can make multiple counters, each with their own internal count using closures.

    function makeCounter() {
                // YOUR CODE HERE
              }
              
              var counter1 = makeCounter();
              var counter2 = makeCounter();
              counter1(); // => 1
              counter1(); // => 2
              counter2(); // => 1
              counter1(); // => 3
              counter2(); // => 2
              
  2. Update makeCounter so that, instead of always starting from zero, you can start from any number, e.g.:

    var counter = makeCounter(100);
              counter(); // => 101;
              
  3. One way we can use closures is as functions that construct other functions. Consider the numerous examples of exponentiation functions that we've created, e.g. square and cube. The following function pow is incomplete:

    function pow(exponent) {
                return function(???) {
                  return ???
                }
              }
              

    Fill in the ??? so that it works like this:

    var square = pow(2);
              var cube = pow(3);
              var power4 = pow(4);
              
              square(5); // => 25
              cube(3); // => 27
              power4(4); // => 256