JavaScript Closure

What is closure ?

Closure is inner function enclosed within another function. It has access to the variables of enclosing scope and global scope.

Closure has three scope chain –

  1. Global scope
  2. Enclosing scope
  3. Local scope

Lets see some examples to understand this –

// global scope
var a = 5;
function enclosing_func(b, c) {
   // enclosing scope
   var d = 10;
  return function closure_func(e) {
    var f = 25;

In above code snippet ‘closure_func’ is a closure. It has access to variable ‘a’ from global scope, ‘b’, ‘c’ and ‘d’ variables from enclosing scope and its local variables ‘e’ and ‘f’.

Some interesting properties of closures

1. Closure has access to its enclosing scope variables even after enclosing function returns. Lets check this with example.

function multiply(a) {
  return function(b) {
    return a*b;

// call enclosing function
double = multiply(2);
triple = multiply(3);

// now call actual closure function
// it still has access to 'a' variable of enclosing scope
result_double = double(12);
result_triple = double(10);


// Output -

As you can see in above example multiply function is enclosing function and it returns the inner closure function. This closure function has access to parameters passed to enclosing function even after enclosing functions execution is finished.

2. Closure stores reference to the enclosing scope variables and not value. So if enclosing scope variable is changes before calling closure, closure will get the updated value.

With above properties, closure can be used to simulate data abstraction. Lets create person object which stores name attribute as private variable and gives access using public methods.

//Person object
function Person() {
  var name = '';
  return {
    getName = function() {
      return name;
    setName = function(new_name) {
      name = new_name;

// create person object
person_obj = Person();

// set name using closure function

// get name using closure function

In above example, name is local variable of Person function. Once the execution of outer function is finished, ‘name’ cannot be directly accessed. We have to use getName and setName functions to access it. This way we can achieve data abstraction.





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s