DEV Community

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

Posted on

Closure, A Confused topic

The closure was really a scary topic for me. Fortunately, I found the video of Namste Javascript [(]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.

Top comments (2)

awalhossain profile image
Awal Hossain

good work. Keep it up

sushantagupta007 profile image
Sushanta Gupta