HTML Dog
Skip to navigation

Closures

A closure is a function that returns a function. The function that is returned (the inner function) is created inside the called function (the outer) so - due to the scoping rules we’ve seen - the inner has access to the variables and arguments of the outer.

Closures are a powerful tool but can be tricky to understand. Mastering them, however, will allow you to write some very elegant code.

Here’s an example:


var saver = function (value) {
    return function () {
        return value;
    };
};

var retriever = saver(10);

alert(retriever());

10

The saver function returns a function that, when called, retrieves the value that was passed into saver. The inner can do so because it was created in the scope of the outer and functions created in a particular scope retain access to variables in the scope even if they are called outside of it.

One way to use closures is for creating functions that act differently depending on what was passed to the outer function. For example, here’s an add function. The value passed to the outer function is used to add to values passed to the inner.


var add = function (a) {
    return function (b) {
        return a + b;
    };
};

var addFive = add(5);

alert(addFive(10));

15

The inner, here saved as addFive, has access to a when it is called because it was created in the same scope as a. The inner adds a and b and returns the result.

In the above example, the inner is saved as addFive because it adds 5 to anything passed to it. A different adding function, using strings, could be created in the same way:


var hello = add('Hello ');

alert(hello('tom'));

Hello tom