Closure - AbhiAgarwal/notes GitHub Wiki
In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.
function derivative(f, dx) {
return function (x) {
return (f(x + dx) - f(x)) / dx;
};
}
For example, the function above is a function called derivative. The parameters you call the function with will be set when you call derivative(1, 2). The function it will return would have a scope where f and dx would be defined as those variables already exist in the returned function.
If we do var a = derivative(1, 2) then the contents of a would be the function that has been returned. Now if you call a(3) then within that function there are 3 variables: f, dx, x that have now been set. The values would be f = 1, dx = 2, x = 3. This is because there is a table storing a reference to each of the non-local variables of that function, and it allows a function to access those non-local variables even when invoked outside its immediate lexical scope.
We have taken this function call out of its immediate lexical scope, and put it into the variable a, but the scope still exists and the function is able to use functions from that scope. The scope exists within the function derivative.
A closure is an instance of a function, a value, whose non-local variables have been bound either to values or to storage locations.
Sources