DEV Community

Cover image for Understanding JavaScript Closures
Raymundo Alva
Raymundo Alva

Posted on

Understanding JavaScript Closures

Today I am going to talk about a very confusing but fundamental topic in JavaScript programming. I had a hard time wrapping my head around JavaScript closures. After a very painful interview question on this topic I decided to really try and understand closures and why they can be useful. I will also do my best to explain it in a clear way. Let’s get started.

So what is a closure? A closure is a function bundled with references to its surrounding state. In clearer terms we could say that a closure is a function inside an outer function that has access to the outer function’s scope. The closure has access to its own variables, the outer function’s variables and the global variables. Just reading this might not make much sense so let’s look at an example.

Closure Example

We have two functions here. The outer function has a variable named ‘a’ and returns the inner function. The inner function has a variable named ‘b’ and accesses the variable from the outer function. After that we save the results of the execution of the outer function into a variable ‘myFunc’. That means that ‘myFunc’ is now holding the inner function. When executed we actually get the sum output on the terminal. Why? At first it might not make sense that this code actually works. In other programming languages, the local variables within a function exist for just the duration of that function’s execution. You might expect that after the outer function executes the ‘a’ variable would no longer be accessible. This is not the case in JavaScript thanks to closures. A closure is the combination of a function and the lexical environment where the function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. This feature of JavaScript allows code like this to run. Things get a lot more interesting when these functions start taking arguments. Let’s take a look at an example.

Closure Implementation

Closures let you associate data with a function that operates on that data. This can be compared to how in object-oriented programming objects allow you to associate data with methods. As you can see we can save the closure into two different variables and the operation on different values. Even though the outer function already ran the environment within it is still accessible to the inner function because it was saved in memory. The environment is stored by the closure for its own later use.

I hope this will help anyone out there understand the basics of closures. It is a very interesting topic and there is still many more things I need to learn about it. Practicing with them will only help more. Questions about closures are frequently asked during interviews so it is very important to understand this concept in order to ace the interview. Happy coding! 😎

Top comments (0)