In JS, functions have a reference to all variables declared in the same scope as well as in any other outer scopes.
Consider the following:
var createCounter = function(n) {
let currentCount = n - 1;
return function() {
currentCount = currentCount + 1;
return currentCount
};
};
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
The inner anonymous function has access to the currentCount
variable. When the inner function is returned by createCounter(10)
, the inner function has access to any declared variable in the same lexical environment scope.