The feature of nested functions is to get values from it. In this case, another function is created inside one function and returned as a result. In the development of interfaces, this is a completely standard technique, the function can then be assigned as a handler for the visitor's actions.
function createCounter() { // LexicalEnvironment = { numberOfCalls: undefined } var numberOfCalls = 0; // LexicalEnvironment = { numberOfCalls : 0 } return function() { // [[Scope]] -> LexicalEnvironment (**) return numberOfCalls++; }; }
As you can see, we received an independent function() counter, each of which, in an unnoticeable way, saves the current number of calls.
If you describe in more detail what is happening:
1) The line (*) starts createCounter() . This creates a LexicalEnvironment for the variables of the current call. The function has one variable, var numberOfCalls , which will become a property of this object. It is initially initialized to undefined , then in the process of execution it will receive the value 0.
2) During execution, createCounter() creates a function in the (**) line. When created, this function gets the [[Scope]] internal property with reference to the current LexicalEnvironment .
3) Next, the createCounter() call is completed.