JavaScript performance library

What are closures?

By quoting Wikipedia:

In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function. A closure—unlike a plain function pointer—enables a function to access those non-local variables even when invoked outside its immediate lexical scope.

The above description of closure may sound a little difficult at first. In fact it is a very simple concept and you will learn it very fast.

What is a closure in JavaScript

Please take a look at the following code:

var counter = function(initVal) {
    var count = initVal;
    
    return {
        increment: function() {
            count++;
        },
        getCounter: function() {
            return count;
        }
    }
}(5);

alert(counter.getCounter());
counter.increment();
alert(counter.getCounter());

At first look it may look like an assignment of a function to counter variable. If you will take a closer look you will notice that there is something at the end of the function block. It’s (5) which, instead of returning the function, executes it. The number inside (5) is a parameter passed to that function.

var counter = function(initVal) {
   (...)
}(5);

The function instead of being returned is executed, so counter variable will contain now output of that function.

By taking a closer look at the function’s return statement we can notice that it returns an object literal consisting of two functions.Thus, our counter variable contains now an object consisting of increment() and getCounter() methods.

By analyzing those two methods we can notice that they access and modify the count variable which is defined and initialized in their parent function.

How those methods can access this variable?

Those methods do not operate on a copy of count variable, but on a reference to it. Inner functions get access to the parameters and variables of the functions they are defined within, thus those methods can access this parameter (count). This is called closure.

Why do we use closures in JavaScript

Usage of closures allows to define private properties that cannot be accessed outside given object. Thanks to that we can be sure that those properties will not be accidentally overrided by other code, which could introduce malfunctions in application.