“Writing in ECMAScript language without understanding closure is like writing Java without understanding classes” — Douglas Crockford, father of JSON
Let’s look at the code below:
However, the above code is not very efficient. It uses a global scope and there is nothing to protect it against change.
You can’t use a value that’s been declared inside a function outside it.
The code below is a closure because x is a variable that is outside of the function.
However, the question then becomes — if a closure is the consumption of a variable outside the function, why is the following code not a closure?
The counter variable in the code below becomes the enclosed variable because it is outside the function being called (i.e. Increment). As a result, you can create an unlimited number of function instances with its own set of unique values.
The variable counter is, therefore, the closure in the code snippet above.
This is particularly useful because closures are stateful functions in that they remember their private variable data after a call. The variables are private because external functions cannot access them with an explicit call for access. This allows for the entire function to be self-contained and its variables are protected against unwanted change.
Writing closures is more than just the act of putting a function inside another function. It is the technique used to create variables that are protected against external change, truly isolated from the rest of the application and are persistently stateful.