Understanding Closure in Javascript

Gary Cordero Rosa
3 min readApr 12, 2021

As you go along the way of learning javascript you hit the concept of closure. Unfortunately for me, it was in the beautiful learning process you go through during an interview. So I write this blog in hopes of increasing my understanding of the topic and hopefully that of my fervent readers.

What is a closure?

A closure in javascript is when functions are bundled together inside another function with references to its surrounding state similar to the following.

At first look, this brought confusion to me not because it was my first time seeing nested functions but because at first look I thought that once the function executed is would return the function but the variable “name” would cease to exist but one I execute the code it was not the case.

This is the magic of closure since it bundles together functions with references to its surrounding state it means it saves the value and reference of the “name” variable. This space where functions are all bundled together is called the lexical environment, in this case, it refers to the whole body of function1().

Immediately I started wondering about the powers of closures and my research led me to a more practical example for this would be the adder function.

This is a widely known example on the internet but it serves as a good base for understanding the practical approach. Another one would be a function that changes the background color of your website.

I made a JSfiddle sample of this code at this link.

A way to see this kind of closure is pretty much like a blueprint to create functions with a similar purpose.

Closures also allow us to emulate private methods.

This is called the Module Pattern in Javascript and if you look very closely it resembles the concept of classes in many other programming languages.

More resources about closure

--

--