So, in this post, I am trying to write down my understanding of Closures and their practical usages, in the hope that it will help some of you.
What is a Closure?
So, what is it? As per the definition
Closure : A thing that closes or seals something
So, a closure is kind of a box with some contents in it.
Lets say, you have a cat and you placed it inside a box along with a bunch of balls and sealed it. So, now the box acts like a closure that closes the cat and the balls. The cat still has access to the balls and it can access them whenever it pleases to do so.
The important thing to note here is that the function that is inside the closure still has access to all the variables inside the closure. As long as the function exists, the variables inside closure will not get garbage collected, letting the function access them whenever it pleases do so.
Coding the Closure
Consider the below code.
As you’d expect, the code will print ‘Hello’ on the console. Now, let’s tweak the code a little bit. Instead of printing the
message, lets return a function that will print the message.
In the above,
- We define a variable
messagethat is local to the function
sayHelloand only accessible from it.
- We declare a function and return it thus returning from
sayHello, all local variables inside that function will go out of scope and garbage collected. Will it happen to
message? Let’s see.
- We call the inner function returned from
- Surprisingly, the code will strill prints ‘Hello’ and we can see that the inner function has access to the variable
messageeven though we returned from the function. This is because of closure.
message (which is accessible to the function) in it. So, when the inner function getting called after we return from
sayHello it still has access to the variable
That explains the basics of Closure. In my next post, I’ll be covering some more examples of closure. Feel free to comment if you have any feedback.