Monday, June 17, 2013

What is closure in Javascript by exmaple code?

var variable = "top-level";
function parentFunction() {
  var variable = "local";
  function childFunction() {
    print(variable);
  }
  childFunction();
}
parentFunction();

Closure:
A Javascript function is defined inside another function, its local environment will be based on the local environment that surrounds it instead of the top-level environment.

Reference:
http://eloquentjavascript.net/chapter3.html