Closures in JavaScript!

Nethmi Jayaweera
2 min readApr 23, 2021

--

Shortest and easiest definition for closure is: they are nothing but functions that preserved data.

Let’s understand this with a simple example. Here we have a function name addTo. we pass a value passed. we have an inner variable which value is 2. And we return the sum of passed and inner values. The outcome of the console will be 5 in the given example. So you can see this is a very simple function which adds 2 to whatever number you pass and return the value.

But in javascript, we can get done the same thing as above without passing the passed variable. What you have to do is just define the passed variable outside of the function as below and make sure to remove the passed variable from addTo function and remove value from the console.log statement as shown below. If we run this we get the same answer 5 as the above example.

Now you may wonder where is closure! Don’t worry, this example itself is a closure. Let’s see how it comes true.

In javascript variables defined outside a function are automatically available inside a function. But how does it works? The answer is closure. So this is the simplest form of closure.

You can have the console output as proof for this code to be an example of closure if we run the function as shown here.

Here passed is not define inside this addTo function.

So what will it do? It will do find this at this scope outside the function. It cannot find it. It will keep going further until it finds it. If it cannot find it, it will be undefined. But if it finds it at any point, then it would add it to the relevant place.

--

--