“Closure is when a function can remember and access it’s lexical scope, even when the function is executed outside of that lexical scope.”
— Kyle Simpson
As we saw in the previous article because of lexical scope a function defined within a function has access to the wrapping functions scope.
The capability for the inner function to continue to reference the outer functions scope even when it is executing outside of the wrapping function is what gives us closure.
##A very rudamentary example of closure##
Here instead of
bam() being executeed inside of
foo() it is returned.
We declare a variable named closure and assign the function
foo() to that
variable and immediately execute it, resulting in the returned function
stored in the variable closure.
On the final line we execute the
bam() function stored in closure and
the value baz gets logged to the console. So even though
bam() is being
executed from outside of the function
foo() it still has access to it’s scope.
N.B. it’s not a copy of the scope it’s an actual reference to the existing scope and is not garbage collected unless that reference is removed.
in event handlers like
For languages with first class functions, the closure mechanism is essential for it to be useful.
N.B. You can have any number of closures over the same scope, there is no limit.
The next post on this topic will be about callback functions, stay tuned!