A closure is a function that accesses variables “outside” itself, in another function's scope, even after the parent function has closed. A closure is able to do this because of a saved reference to the lexical environment it was initially defined in. Thus, a closure gives our functions persistent memories.
Let's take a look at an example.
In the above example, we are saving the result of the outer function into our variable myFunc. When we do this, not only is the internal function of the incrementCounter saved, but also the variable counter. This bundle of the function along with the variable is what is called a closure. This is because of a saved reference to the lexical environment.
So if the combination above is collectively a closure, what exactly is counter and what should we refer to it as? It is basically data stored that is carried with the internal function to be stored in global memory. Some call this “Persistent Lexically Scoped Reference Data”.
We can also say that the counter variable is “closed over” by the internal function of incrementCounter. Are closures memory efficient? Yes. By using closures, we can create variables that are stored in memory to be used in the future.
What will be the result of the following?
1 and 1. Every time we invoke the outer function, we reserve some space in local memory that will contain all the variables and arguments. When we finish running the outer function, that temporary memory will be deleted. So when we invoke the outer function again, there is no previously stored memory to access.
What will be the result of the following?
1 and 2. A closure will be created when the function is returned from another function, as on line 12. And because of this closure, we will have persistent lexically scoped reference data that we can access.
What will be the result of the following?
1, 2 and 1, 2. Multiple closure instances don't share the same persistent memory.