Wednesday, 12 August 2015

How do closures work in Javascript

How do closures work in Javascript


Question: What is closures?
Whenever you defined a the function within another function, the inner function has access to variables in the outer function.


Following are Simple example of closure.
function mainFunction(outerData) {
  var mainFuncData = 3;

  function innerFunction(innerFuncData) {
    console.log(outerData + innerFuncData + (++mainFuncData)); // will alert 16
  }

  innerFunction(10);
}

mainFunction(7); //17


Question: Why it can access to variables in the outer function?
Because It is defined as var , which means it is global variable.