Closures in Javascript

Natalia Wit
2 min readNov 22, 2020

Closures mark an important topic in JavaScript but also a very confusing one for new developers.

What are closures?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

In other words, let’s think of closures as a home and the only people that have access to items inside of your home are anyone who lives there.

In the above example, outerFunction creates a variable called name and an inner function called alertName — which is only available within the outerFucntion function. Inner functions/nested functions have access to variables in the outer function, in fact, this is why displayName has access to the name variable declared in the parent function, outerFunction().

If you run this code in the console, you will see that the alert pops up in the browser with the name variable’s value which is defined in the parent function. This is an example of lexical scoping — which in fact means the location where a variable is declared within the source code to determine where the variable is available.

Conclusion

Closures come up in interviews commonly, it is important to know what a closure is and how to create one. Make sure you play around with a few examples and get familiar with the topic!

--

--