What is Closure in JavaScript?

Please explain with an example.

To understand concept of closure go through each line and concentrate on the code carefully:

 

function tempFunc() {
  var name = 'Laptop'; // name is a local variable created by tempFunc
  function printName() { // printName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  printName();
}

 

function testFunc() {
  var name = 'Laptop';
  function printName() {
    alert(name);
  }
  return printName;
}

var myFunc = testFunc();
myFunc();
Running this code has exactly the same effect as the previous example of the tempFunc()

function above. What's different (and interesting) is that the printName() inner function is

returned from the outer function before being executed.

 

At first glance, it might seem unintuitive that this code still works. In some programming languages,

the local variables within a function exist for just the duration of that function's execution.

Once testFunc() finishes executing, you might expect that the name variable would no longer

be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.

 

The reason is that functions in JavaScript form closures. A closure is the combination of a

function and the lexical environment within which that function was declared. This environment

consists of any local variables that were in-scope at the time the closure was created. In this case,

myFunc is a reference to the instance of the function printName created when testFunc is run.

The instance of printName maintains a reference to its lexical environment, within which the variable

name exists. For this reason, when myFunc is invoked, the variable name remains available for use,

and "Laptop" is passed to alert.

Here's a slightly more interesting example—a testAdder function:

function testAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = testAdder(5);
var add10 = testAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12
In this example, we have defined a function testAdder(x), that takes a single argument x,

and returns a new function. The function it returns takes a single argument y, and returns

the sum of x and y.

 

In essence, testAdder is a function factory. It creates functions that can add a specific value to

their argument. In the above example, the function factory creates two new functions—one that adds

five to its argument, and one that adds 10.

 

add5 and add10 are both closures. They share the same function body definition, but store different

lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.