Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
The definition of closure is as follow:
A closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.
To understand closures, we must first understand scopes. The scope in a program is a set of rules for storing variables in some location and retrieving them later. Certain structures in a program create their own scopes. If I declare a variable inside a scope, it is not accessible in an other one.
We have three different scopes here: the global, the one created by the if block and the one created by the function func.
Back to closures
So now, we understand a bit more about scopes. Closures allow a function to access its scope when that function is executing outside of its scope. Let's see this in action.
Why is this a closure? To be a closure, this would mean that the function inner is being executed outside of its lexical scope and still having access to its scope. So what happens here? The function outer returns a reference to the inner function. We execute the outer function and pass it to the func variable. Then we execute the inner function by calling func(). inner is executed, but outside of its declared lexical scope. It's executed outside the outer function. In theory, the program would free up space and see that our outer function is no longer needed ( garbage collector ).
inner has a lexical scope closure over that inner scope of outer. This keeps the scope alive for inner to use. The reference that inner has in the outer scope keeps that scope alive. ==> CLOSURE.
Ok, it's still a bit blurry. Could you give me more examples? Perhaps real-world ones? What about callbacks?
timer has an reference to the chrono inner scope( with the message variable ). That scope is kept alive even after 1 second where the chrono is clearly no longer needed by timer. Because that scope is still alive, timer can print 'GOGOGO' (the message variable) every second.
One last example. Let's look at the famous module pattern.
Module Pattern! sayMyAge and sayMyName are both executed outside of their lexical scope. But because both have references to the myModule inner scope, the scope is kept alive for them to use the name and age variable.
I am sure you have used closures in the past without you knowing it. Look at the code you wrote in the past and try to spot the closures you wrote. In the next playgrounds, we will dig deeper in functional programming and the use of closures.