Javascript: Closure

Deepak jha
2 min readJan 17, 2021

In this blog, I will share my knowledge about the closure in javascript.

The closure is one of the important concepts in javascript and also a little bit confusing. So as you already know javascript defines two types of scopes which are Global and Local and if you don't then let me explain.

A global variable declared outside a function belongs to the global scope and result of this, it can be accessed from anywhere in our code and Local variable are those variables which are declared within the function and as a result of it, these variable or only accessible within the function and any nested function.

Example

This is a very simple example of closure, and I think you probably don't even realize that. The name is a global variable and it can be accessed from anywhere and id local variable and only accessible inside function printName. I hope at this point you understand the scopes in javascript.

Closures in javasript is a feature where an inner function has access to the outer function’s variables.

Example

This example is the most common use case of closure and as you can see we have a function outerFunction and this function returning another function inside of it called innerFunction and in the last, we are calling outerFunction, and after we can calling out function.

What really happening here is that where first call outerFunction and we have outerVariable which we set to “outside” and then we an innerFunction which is returned and the reason we are able to access outerVariable inside the innerFunction is because of closures.

Now you might be thinking how it is possible if outerFuction complete its execution and after that outerVariable is no longer accessible then how innerFunction is printing the outerVariable.

So what happens here is, when innerFunction has access to outerVariable it going to saves it and it makes sure it knows what is outerVariable even if the function that defines outerVariable is no longer executed anymore, it still keeps track of outerVariable.

The most common use of closure is to have variables that we passed into functions that can be accessed inside other functions.

--

--