Brief – JavaScript Closure

I am still in my early stages of JavaScript programming. Through my learning, I find closure is a very powerful concept in JavaScript. But it can seem somewhat confusing at times specially if coming from object oriented background. So in this post I am briefly penning down the concept just so that it can be to quickly anytime.

For in-depth understanding, please look at references mentioned at the end of the post

The formal definition of Closure as given by Douglas Crockford is:

The inner function always has access to variables and parameters of outer function, even after the outer function has returned.

Meaning if there is a nested function that accesses a variable declared in it’s outer scope (the parent function); in this case even if the outer function has finished its execution, the referenced variable still remains in the scope.

In order to understand the definition better let’s first take a look at how a non-closure looks:

function notAClosure(){
   var x = "some variable in outer scope";
   function nestedFunc(){
      alert("Nested function that does some stuff");
   }
   return nestedFunc;
}

As we can see here, the variable x which is defined inside notAClosure function will go out of scope as soon as the function has finished executing.

Now let’s write same example with Closure

function closure(){
    var x = "I am a variable inside the closure";
    var nested = function nestedFunc(){
       alert(x);
    }
    return nested;
}
var c = new closure();
c.func();
// alert box with message: "I am a variable inside the closure"

Here the variable x is in scope even if the function closure() has finished executing. It can be accessed via property of the object literal returned.

Therefore, a closure can be thought of as a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

This behavior is useful specially when we want to emulate the concept of classes in JavaScript, we can achieve it by creating closures and accessing variables in nested function, in which case they remain loaded in the memory similar to member variables of a class. This is powerful when creating modular structure of a JavaScript code.

Benefits:

  1. Create closures to emulate the concept of class/object
  2. Use closures to implement the concept of binding and encapsulation
  3. Use closures to define private scope and reveal them through modules

Caution:

Be aware of closures in for loop, which can be addressed by using a function factory or by using ‘let’ keyword.

References:

  1. Closures – MDN
  2. Understand Javascript closures with ease