Closures in JavaScript are one of most important and interesting concept.However if you don't understand them you may find them not interesting.
In this article, i will try to make closures more interesting for you.
Before going into the world of closures, let's first understand lexical scoping. Let's take a closer look:
From the output above, the inner function can access the outer function's variable. This is lexical scoping, where the scope and value of a variable is determined by where it is defined/created.
So what is a closure?
A closure is created when an inner function has access to its outer function variables and arguments. The inner function has access to –
- Its own variables.
- Outer function's variables and arguments.
- Global variables.
Closure is when a function is able to access its lexical scope, even when that function is executing outside its lexical scope or, Inner functions can access its parent scope, even after the parent function is already executed. For example:
Here we are returning the inner function and executing it later. In some programming languages, the local variable exists during the function’s execution. But once the function is executed, those local variables don’t exist and they will not be accessible.
Here, however, the scene is different. After the parent function is executed, the inner function (returned function) can still access the parent function's variables. Yes, you guessed right. Closures are the reason.
The inner function preserves its lexical scope when the parent function is executing and hence, later that inner function can access those variables.
More examples of closures.
Every time you call countValue, the count variable value is incremented by 1. Wait – did you think that the value of count is 0?
Well, that would be wrong as a closure doesn’t work with a value. It stores the reference of the variable. That’s why, when we update the value, it reflects in the second or third call and so on as the closure stores the reference.
Let’s look at another example:
This happens because countValue1 and countValue2, both preserve their own lexical scope. They have independent lexical environments.
That’s it! I hope you can now say that you find closures interesting.
Top comments (0)