Jennifer Bland header image
≡ Menu

Understanding Closure in JavaScript

A closure is a function object that retains ongoing access to the variables of the context it was created in (even after the outer function calls it was created within have returned).

In other words, the function defined in the closure ‘remembers’ the environment in which it was created.

Let me give you an example:

function getName()
  var firstName = 'Jennifer';
  function showName()
    alert(firstName);
  }
  showName();
}
getName();

In the above example, firstName is a local variable created by getName function. The getName function also creates a function called showName.

The showName function is only available within the body of the getName function. The showName function has not local variables of its own. However, it has access to the variables of outer functions and so can use the variable firstName declared in the parent function.

Normally, the local variables within a function only exist for the duration of the function’s execution. Once getName() has finished executing, it is reasonable to expect that the firstName variable will no longer be accessible. But since the alert displays the value of the firstName variable then this is not the case.

The reason is closure. A closure is a special kind of object that combines two things:

  1. A function
  2. The environment in which that function was created

The environment is what makes closure possible. The environment consists of any local variables that were in scope at the time that the closure was created. In the above example the variable firstName was available making it accessible to the showName function.

by Jennifer Bland

I am a Google Developers Expert. Entrepreneur. Mountain Climber. Neil Diamond fanatic. World traveler. MBA grad. Software Engineer. Interested in hiring me? Contact me at ratracegrad@gmail.com

1 comment… add one

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.