Closure explained in an elevator
There are plenty of articles discussing about the closure, too many to be listed here. They all eventually incorporate long code examples in various languages into the explanation, which is fine. Many articles choose to use the word close over to describe about closure, which does not really mean a whole lot, at least to me.
I attempt here to explain about closure here without showing any code, hence “in an elevator”.
A closure is simply a function defined inside another function. This inner function naturally has access to variables and constants defined in its outer function. This inner function can even modify the value of these variables (of course, the inner function cannot modify any constant, no matter where the constant is defined). That’s not all, this inner function also has access to arguments that get passed to the outer function. All of these facts are neither surprising nor interesting. But that’s all. That’s the definition of a closure. It’s easy to visualize. It’s easy to understand. A closure is an inner function that naturally has access to variables, constants and arguments of its outer function.
If the inner function is NOT returned by its outer function, all of the variables defined in the outer function and the inner function itself will cease to exist once the outer function returns or exits. Used in that way, a closure which is the inner function is nothing more than a small utility, helper function of a larger outer function.
What makes closure interesting is when this inner function is returned by its outer function. The caller of the outer function would save this returned inner function in a variable, which can later be invoked. When this happens, variables, constants and arguments of the outer will continue to exist even after the outer function has returned. This fact leads to many usages and patterns which makes closure a powerful concept.
That’s a 2 minute explanation with no code. Now we can exit the elevator.