Closures in JavaScript

Saturday, March 07, 2015
Understanding closures in JavaScript gives ways to various possible solutions that makes the program better. Once you start using closures in your programs, you will appreciate the possibilities it provides for creating better code. This is one of the feature that makes JavaScript interesting. Some find this confusing, but it is easy to use and very useful once you get the hang of it.

What is a closure?

Closure is all about how the variable names are resolved in nested functions even after the outer function has returned. Closure is also known as lexical scoping/static scoping. Consider the following example,


 * foo() - Outer function
var closure = (function foo() {
  //{{ variables
  var users = {
    1: 'UserNameOne',
    2: 'UserNameTwo',
    3: 'UserNameThree'
  // returns this inner function, after self invocation.
  return function (id) {
    return (id === undefined ? 'User not available' : users[id]);
}()); // self invocation(important).


The above code shows how the closure is created. When a self invoking function returns an inner function, it returns the function with access to the variables inside of foo() which is closure.
It is important to remember that the outer function must execute immediately as shown above for it to return the closure. See how the function is wrapped inside params and executed.
// self invocation
var closure = (function name(){

How it works ?

In the above code, the context of the inner function includes the scope of the outer function in which it is present, even after the outer function foo() has returned. That is, the returned function (called closure()) has access to the variables that was present in the outer function.

Benefits of Closure

Closure is useful when you want to avoid variables being stored in the global scope and also to avoid conflicts with variable defined with the same name in some other libraries and scripts.

Debugging Closure Script

Debugging the closure script

As you can see in the above GIF, the closure is created during the function return statement. Inside the scope of the inner function, it has a closure property which has access to all the variables present in that particular scope(i.e the variables in the outer function). Once the closure is created and returned, that function can still access the users variable through closure.