top of page

How to use closures in JavaScript

What is closures and how does it work? This is a question many developers ask themselves when they first start learning JavaScript.

​

Maybe the easiest way to teach someone what closure is by showing them what is not closure. A function that is not dealing with closure is a function that is only depending on it's own arguments and internal data. Let us look at an example. 

This function is not depending on anything else that it self. As long as someone calls this function an provide the arguments it will do just fine. When this method is called it is paced on the stack and executed, and when it's done it is called of the stack. In other words, it just lives in memory for as long at it's used.

​

So when is something a closure? When a function is having a reference to variable or function outside it own scope the runtime/interpreter needs to store these values. To do that it creates a closure which is then stored in the heap memory to have access to them later. The heap is long lived, so not like the stack that is short lived. So a closure is not just a function. It is a function that is combined with the state outside the function, also called the lexical environment. 

Let's again look at an example.   

As you now can see, the function now has a reference to a variable outside it's own scope. This is now a closure

Another way we can create a closure is to create a function with some state and a inner function that access this state. Again let's look at an example.

The interesting here is that funB has access to the state in funA, but funA has no access to the state in funB. Since funB has a reference to state outside it self it is a closure

​

Now you might wonder...why is this important? What does closure really do?

​

The trick here is to understand that the heap is for long running processes and that the state you are referencing might mutate(change) over time and might not be what you expect it to be...if you are not aware of how it works. 

​

Something to remember is that when you reference state outside your scope and create a closure, is that the function that you just created might not be the only function that access the outside state.

 

So now you know a little bit more what closure is and we hope we where able to help you on your journey in learning JavaScript.

 

We hope that we where able to teach you about closures in a simple, human readable way. There is a lot more that could be said about closures and there is other pages on the internet that goes more in depth on the subject. So if you want to know more, we can recommend visiting this page for more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures.  

©2022 - 2024 by JavaScript Schools.

bottom of page