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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
awalhossain profile image
Awal Hossain

good work. Keep it up

Collapse
 
sushantagupta007 profile image
Sushanta Gupta

Thanks.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️