Understanding and Applying Closures in JavaScript

Learn closures in the simplest way possible

Divine Favour
Better Programming

--

Lightbulbs
Photo by Dragos Gontariu on Unsplash.

I remember the first time I came across the term closure. It was on an Instagram post listing out some important JavaScript topics.

After seeing this post, I tried to find a simple tutorial on closures. I went through so many examples, but I still wasn’t getting a grasp on it. Most of the tutorials I came across online never gave real examples that could be easily implemented. This made it very difficult for me to know how and where to use closures.

At some point, I thought of just forgetting the topic and advancing to other JavaScript topics. Closures may indeed seem very overwhelming.

However, once you get the hang of them, you’ll instantly become a much better programmer.

What Closures Really Are

A closure is a feature on JavaScript that allows you to access a parent function’s scope from a nested or a child function.

In their simplest form, closures are functions with preserved data. A closure is created every time a function is created.

Closures give us the ability to store data in a separate scope and access it only when necessary.

A simple reason why we need closures is to give some of our data privacy. Sometimes we want to define variables that should only be accessed from a specific part of the script. Closures are best suited for such cases.

A simple example

In this example, we will create a function that is nested inside another function. The child function accesses the variable stored in the parent function:

Here, we have a function named returnMsg that has access to the variable of the parent function writeMsg. This implies that returnMsg has access to the msg variable. In this example, returnMsg is the closure.

A practical example

Closures can come in very handy when you want to associate data with a function that operates on that data. This is similar to object-oriented programming, where objects allow you to associate the object’s properties with one or more methods.

Therefore, you can use a closure anywhere that you might normally use an object with only one method.

Instances where you might want to do this are very common. Most of the code written in frontend JavaScript is event-based (it takes effect only when a user interacts with the web page in a certain type of way). You define some behavior and then attach it to an event that is initiated by the user (such as a click or a double-click). The code is attached as a callback (a single function that is executed in response to the event).

For instance, assuming we want to add buttons to a page to adjust the width and height of a div element anytime a user clicks on any of the buttons:

Here, the width and height are first set to 60px and 50px, respectively.
We created three buttons. Each of them increases the div element to a particular size anytime the user clicks on it. Each button calls a function.

The increment is done by the adjustOne, adjustTwo, and adjustThree functions inside the adjust function.

Another example

Suppose we want to create a counter that increases the number of claps when the user clicks on a button:

A parent arrow function that is self-invoked is created. The number of claps is first initialized to 0 inside the parent function addClap. A child function is used to increase the counter by one anytime the user clicks on the button.

From this, we can see that the clapCounter variable was declared outside the child function, but we were able to access it from inside it.

This is basically the simplest form of closures.

Closure Scope Series

A closure has three scope series:

  • A lexical scope or static scope. This scope accesses its own variables.
  • A parent function scope. This scope accesses the variables of its parent function.
  • Global scope. This accesses any variable outside a function (i.e. global variables).

Lexical scope

Lexical scoping means that a variable defined outside a function can be accessible inside another function. However, the reverse does not hold true. The variables defined inside the inner function cannot be accessed outside that function.

This means that variables of parent functions can be accessed by their child function, but variables of child functions cannot be accessed by parent functions.

Suppose I have a parent function x with variables defined inside it and a child function y that also has variables defined inside it. The variables of y can only be accessed inside y. It is private, while the variables of x can be accessed in both functions x and y.

A lexical scope is also referred to as a static scope. The concept of lexical scoping is widely used in closures.

A simple example to demonstrate a lexical scope:

In the code snippet above, two functions were created: myFunction() and mySecondFunc(). myFunction() is the parent function that has a function scope, while mySecondFunc() is the child function that has a lexical scope. Both functions have variables defined inside them (age and hobby, respectively).

The age variable can be accessed from inside both functions, but the hobby variable can only be accessed inside the mySecondFunc() function.

The name variable has a global scope, so it can be accessed from anywhere in the script.

Tip: Avoid using global variables.

Conclusion

This is as far as I will go in this overview of closures. You might have been using closures without even realizing it, but if you haven’t, give them a try.

From here on out, when you see closures in your code or any code you see on the web, you can easily pinpoint them, see what they are doing, and why they are being used.

There is nothing more to it than practice. You now have the basic knowledge. Dig into some existing code — whether it’s yours or any code you can lay your hands on — and try to identify the closures and why they are used. The more you practice using closures, the better you’ll understand the topic.

Thanks for reading. I hope this article helped you better understand closures.

Reach out and ask me questions in the comments if you have any!

--

--

Hi✋ I'm Divine🙂 A Frontend Developer excited about sharing helpful coding tips😊💻