And it is justified.
The closure is such a non-trivial concept that you might have already used it without realising it.
We will see some real development scenarios that involve closures, but first, let us understand what closure actually is.
The entire concept of closures is based on scopes. And scopes decide where can we access a variable or function in our program. As simple as that. Scoping defines which parts of your code can access what. Take a look at the example below to understand scoping better.
In the case of the previous code snippet, when we are accessing variable
a in the
Now we have enough ground to learn closures.
A closure is function bundled with its lexical scoping.
To put it in simple words, when a function is accessing variables from outside of its scope, the function and those variables form a closure.
Why do they form a closure? — Because, when that function is executed, even if the parent scope has finished executing, it will still need those variables. This typically happens when we are returning functions from functions.
Let us look at an example to understand this better.
Let us dissect what is happening here:
outerVariableis declared in
outerVariableand it is returned without executing.
- When line number 11 is executed, scope for
- But when we execute
returnedFunction, it still prints value of
- So what happened is:
innerFunctionwas returned with variables from the outer scope bundled together. So in other words, a Closure was returned.
THAT'S IT!! That is all you need to know about closures. Of course, there are some other complicated examples. It will be easier for us to understand those now.
One important caveat with closures is that closures hold references to variables from the parent scope. Not the values. So functions with closures can change values and get updated values. This will be useful in other real examples listed below.
Real-world applications of closures
As I mentioned earlier, you might have used closures without realizing it. Following are some use cases I have encountered where closure was a better solution.