Tulamthings

What is closure in JavaScript

I'm on the journey to learn deep dive into the JavaScript language. So I want to re-explain what I have read in the book. Today's topic is closure.

The closure is the most important concept and I encountered it often when I start to learn JS deeper. Not only JavaScript but also other languages like python,...

So what the hell is Closure and why it is important. To fully understand it. We have to know some other concepts first.

Outer function, Inner function and Free Variable

Let take a look at the example

jsx
function outer() {
let name = "Ted Mosby";
function inner() {
console.log(`Hello, ${name}`);
}
inner();
}
outer() // output - Hello, Ted Mosby

Defining a function inside another function is a common pattern. We call the inside function is Inner function and the outside function is Outer function.

The name variable called Free Variable because it's a local variable of the outer function but also global variable of the inner function (not really, I mean it's not a local variable of inner function).

The inner function can access the variable of the outer function.

Closure

Before define what is closure. Take a look at the example

jsx
function outer() {
let name = "Ted Mosby";
function inner() {
console.log(`Hello, ${name}`);
}
return inner;
}
const inner_func = outer()
inner_func(); // can you guess the output?

Do you see a slight difference from the previous example? Instead of calling inner function directly within the outer function. We return the inner function, then assign the inner function with a variable and finally execute the inner function.

The output of this example will be the same as the above example. But we all know that after the outer function executed. JavaScript will delete the namespace of the outer function. It means that we no longer access to the name variable because it doesn't exist. So why we have that output?

That because of closure. Thanks for it help we still can access to outer variable even the outer function had been executed.

In the second example. You see that we return the inner function. But actually, we are returning a closure, and that why we can still access to free variable name. In other words, closure included 2 parts, the free variable it's using (in this case is the name variable) and the inner function is returned from the outer function.

In conclusion, closure helps us to access the parent's variable even after the parent's function has already executed.

Share this post