3.2 Closures

The Mozilla development network defines closures as follows:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

Getting Ready

All you need to be able to use closures is an installation of TypeScript 2.0 or higher.

How to do it…

We are going to implement an object which will allow us to increment and decrement the value of a numeric counter. However, the counter itself will remain private thanks to the usage of closures:

const counter = (function () {
    let i = 0;

    const counter = {
      next: function () {
        i = i + 1;
        return i;
      },
      prev: function () {
        i = i - 1;
        return i;
      }
    };

    return counter;
  })();

If we invoke the methods next and prev, we will be able to observe how the value of the counter changes:

counter.next(); // 1
counter.next(); // 2
counter.next(); // 3
counter.prev(); // 2
counter.prev(); // 1

How it works…

The preceding examples uses two functions (prev and next) defined inside a closure (the IIFE function). The two functions refer to independent free variables, or, in other words, remember the environment in which they were created. In this case, the only free variable is the counter named i, this explains how is it possible that the counter is not cleared from memory after the closure (the IIFE function) has been executed.

Closures can be used to emulate static and private variables at runtime but they can lead us to memory that will never be freed, so make sure that you are careful when you use them.

Source Code

Closures

See also

Please refer to the recipe about Immediately-Invoked Function Expressions to learn about more practical usages of closures.


Shiv Kushwaha

Author/Programmer