#What is a closure?#
function retirement(retirementAge) {
var a = " years left until retirement";
return function(yearOfBirth) {
var age = 2019 - yearOfBirth;
console.log(retirementAge - age + a);
};
}
var retirementUS = retirement(66);
retirementUS(1970);
retirement(66)(1970);
In the example code above, the outer function is still able to access variables and arguments from the outside function (scope) even when the outside function has stopped its execution (returned).
An inner function has always access to the variables and parameters of its outer function, even after the outer function has returned.
Closures are used for data privacy.
Why does it work?##
Even if the function execution is removed from the execution stack, the function scoope still remains in the scope chain. The variable object of the outer function remains within