Usage of Closure in Javascript

Neeraj Singh

By Neeraj Singh

on March 13, 2009

In this article you are going to see what you can do with the power of Closure in Javascript. This not an article about what Closure is. This is an article about what Closure can do. I see a lot of people asking the question what's the big deal with Closure. They want more real world cases where Closure will make sense.

Example 1: Getting digit name

The goal is to read from an array and display the result. The first implementation is to put everything in Global namespace.

1var names = ["zero", "one", "two", "three", "four", "five"];
3var digit_name = function (n) {
4  return names[n];
7alert(digit_name(3)); // 'three'

Above solution works. However creating a global variable names is not a good thing. You should create as less global variables as possible.

Moving to a function

Next step is to move the code to a function. In this case we will not have any global variable.

1var digit_name = function (n) {
2  var names = ["zero", "one", "two", "three", "four", "five"];
3  return names[n];

The above solution is very slow. Every single time the function is called the whole array is loaded. This solution works and most of the developers will settle with this one. However Closure can provide a better solution.

Better solution with Closure

1var digit_name = (function () {
2  var names = ["zero", "one", "two", "three", "four", "five"];
4  return function (n) {
5    return names[n];
6  };

Note that after declaring, the function is also getting invoked. This is a case of self invoking function. You can find out more about self invoking function here .

Example 2: Getters and Setters

Developers deal with getters and setters all the time. However creating a good getter and setter could be a little tricky. Here is one implementation

1function Field(val) {
2  var value = val;
4  this.getValue = function () {
5    return value;
6  };
8  this.setValue = function (val) {
9    value = val;
10  };
13var field = new Field("test");
15// => undefined
18// => "test2"

Above solution works and it's nicely done.

Let's look at another implementation.

1var getValue, setValue;
2(function () {
3  var secret = 0;
4  getValue = function () {
5    return secret;
6  };
7  setValue = function (v) {
8    secret = v;
9  };
13getValue(); // foo

Example 3: Building an iterator using Javascript

1function custome_iterator(x) {
2  var i = 0;
3  return function () {
4    return x[i++];
5  };
8var next = setup(["one", "two", "three", "four"]);

This is a simple case of serially iterating through the items provided but the logic of deciding next element can be complex and it can be private.

Closure is a big topic and a lot of people have written a lot about it. Just search for Closure and you will get tons of links. I refer to this article time to time to see what pattern to use to make best usage of Javascript Closure.

This article was inspired by this book, this video and this article .

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.