Javascript Closure

The closure is a way to remember and continue to access a function's scope generally its variables even once the function has finished running.

Example :
var fun1 = function myAddFun(x)
{
  var fun2 = function add(y)
  {
    return x + y;
  }
  return fun2;
}

var funCll = fun1(12);

funCll(8);


Inner function "add" uses variable x. When we call "func1", it assigns the value 12 to the x, and return the reference of inner function "fun2". Now the variable "funCll" hold the reference of inner function "fun2" with an internal value of x=12. When we call "fun2" with reference on "funCll", the addition of the value of x=12 and parameter 8 occurs, cause the result 20.

In above program:

Inner function `add()` uses `x`, so it has a "closure" over it.

Comments