Let’s begin with a definition of a closure. A closure is essentially a function whose body references a variable that is declared in the parent scope.
The key to understanding closures is to grasp two other programming language concepts: lexical scoping and free variables. Let’s look at lexical scoping first, and then dive into free variables.
Lexical scoping rules serve to answer one question: what is the value of this variable at this line? In short, lexical scoping says that whichever assignment to a variable that is the closest gets that value.
The value of a variable x is given by the innermost statement that declares x. Furthermore, the area in a program where a variable ...