The closure is an inner function that has the access to the outer function’s variable. And it is a combination of function and lexical environment within which that function was declared.

The closure has three scope chains

  1. It has access to its own scope (variables defined between its curly brackets)
  2. 2.It has access to the outer function’s variables
  3. It has access to the global variables

And the inner function has access not only to its outer function’s variables, but it has also access to the outer function’s parameters. The very vital point to know about closure inner function is they cannot call to the outer function’s argument objects

Lets see simple example of closure


In this example a is a global variable. In a web page, global variables belong to the window object.Global variables can be used (and changed) by all scripts in the page (and in the window).A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code. Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Lets see another example of closure


Run this example, we have defined a function createAdding(x), which takes a single parameter x and returns a new function. The function it returns takes a single parameter y and returns the sum of x and y. The createAdding is a function factory — it creates functions which can add a specific value to their parameter. In the above example, we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10. adding5 and adding10 are both closures. They share the same function body definition but store different lexical environments.