All Articles

A Primer on Closures

A closure is two things: a function, and the environment that function was created in. To create a closure, a “factory” is needed; a function that creates functions.

makeAdder :: Integer -> (Integer -> Integer)
makeAdder x = \y -> x + y

makeAdder is a “factory”, it is a function which creates adder functions. More specifically, makeAdder is a function that creates closures because every result will retain the value of x for later use.

addTen :: Integer -> Integer
addTen = makeAdder 10

In this example, addTen is the closure since the environment keeps x = 10. This value is stored for later use whenever addTen is invoked.

> addTen 11 
Output 21

Private Variables

One of the most common use cases for closures is private variables. In some programming languages, like JavaScript, there is no special syntax for it. As a result, a commonly used pattern called the module pattern is utilized.

var MakeCounter = function() {
  var __actions = {};
  var __count = 0;
  
  __actions.show = function() {
    return __count;
  };
  
  __actions.increment = function() {
    __count = __count + 1;
  };
  
  __actions.decrement = function() {
    __count = __count - 1;
  };
  
  __actions.reset = function() {
    __count = 0;
  };
  
  return __actions;
};

var myCounter = MakeCounter();

In this example, myCounter is a module which contains an environment that has a counter, named __count. There is also an __actions object which has functions. Each function is a closure, since they all exist within the same environment that shares __count.

For good measure, here is the same code written in TypeScript. TypeScript is a superset of JavaScript which contains explicit types and other classical features.

class Counter {
  private count = 0;

  increment() {
    this.count = this.count + 1;    
  }

  decrement() {
    this.count = this.count - 1;
  }

  reset() {
    this.count = 0;
  }
}

This code is more expressive due to the fact that private is being used. It is also less lines of code, and has the added benefit of sharing parallels with classical programming.

Summary

Closures allow functions to save an environment which they can later reference, this was helpful when implementing a counter. The counter uses the module pattern, which leverages closures, to access a variable which is private. Using this pattern is so common, that TypeScript exposes syntactic sugar as a shorthand for creating private variables.

Published 10 Dec 2015