DEV Community

Cover image for Closure, A Confused topic
Sushanta Gupta
Sushanta Gupta

Posted on

2

Closure, A Confused topic

The closure was really a scary topic for me. Fortunately, I found the video of Namste Javascript [(https://www.youtube.com/watch?v=qikxEIxsXco)]of the closure concept and I believe I understand closure.

First let's observe the following code block
`
function outer () {
let a = 5;
function inner (){
console.log("From Inner",a)
}
return inner;
}

const myFunc = outer();
`

Here, the outer function is returning the inner function. We are assigning the returned result of the outer function to the myFunc variable. There is nothing new till this point.

However, what happens when we assign the returned result of the outer function. If we console.log myFunc we will see the following result.

ƒ inner (){
console.log("From Inner",a)
}

But if we call the myFunc() then, we get the result 5. How is it possible?

The question is how inner function gets the value of a, which is declared in its parent scope?

The answer is when the inner function is returned, then not only the function is returned but also the variable is returned. This is called closure.
Imagine this way,

imagine closure in this way

So a closure is like an envelope/box that contains a function and the variables required for the function.

Simply, closure is a function along with lexical scope bundled together.
Hope you have understood the closure concept.
Thanks for reading. To make me inspired, please write your feedback in the comment section.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (2)

Collapse
 
awalhossain profile image
Awal Hossain

good work. Keep it up

Collapse
 
sushantagupta007 profile image
Sushanta Gupta

Thanks.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay