Closure in JavaScript
You all must have heard about this term all the time in interviews , on diff js websites pretty much everywhere. Let’s have a discussion on it today
- What is Closure?
In simple terms if I have to explain this to anyone I will say when we want to use something of local scope as global scope we use closures.
We all know that if we define a variable inside a function then we can’t use it inside another function. Right?
Here comes the closure, using it we can use a variable define inside one function in another function. Let’s take an example.
In the above example we are writing a simple sum function and in return we are returning another function. Try writing how you will do this example without closure and try to identify pros and cons of both.
Get Priyanka’s stories in your inbox
Join Medium for free to get updates from this writer.
Now what is happening is example:
When we see function sum , variable a of function sum and function add are in same scope of function sum because of which variable a is being accessed by function add later on.
You can call a() any number of times passing different values ,try to check the output.
- Basic uses of closures:
Implementing Currying concept
To have the protected private behavior of OOPS
Have fun writing and trying different examples using closure.
Hope this helps you !!!




