PART II: Closures in Javascript

Benyam
3 min readMay 12, 2021

In part one we got ourselves familiarised with Closures in javascript. Part II will be exploring some non-trivial cases and the pros and cons of closure as a feature to javascript.

In the following code block, we can see that the API_URL the variable is being passed to the fetch method because this variable binds to the one defined before the fetch function’s call/invocation because it is not defined elsewhere. Talk about being so needy- this is a joke. [This example is taken from a project I did in the past]

async function getShowsEpisodes(showId) {let API_URL = “http://api.tvmaze.com/shows/" + showId + “/episodes”;const fetchResult = await fetch(API_URL);const data = await fetchResult.json();makePageForEpisodes(data);}

To put it seriously and succinctly, if a variable is referred to but not defined inside a function, it will resolve (or bind) to a variable that was created outside of the function body.

The Nexus between Scope, setTimeout, and Closure.

Imagine you want to print numbers say between 1 and 10 after a delay of 1 to 10 seconds- 1 after 1 second, 2 after 2 seconds, etc.

Let us give it a try and see the output.

So what do you think is the output?

Welcome to Javascript madness! But seriously how is this possible? This is so because of closure or rather a lack thereof. Yes, I said that. You see since javascript doesn’t wait for the setTimeout function the question “Does this surprise you?” gets printed first. While this is happening the variable counter has run up all the way to 11 and that is why it is printed 10 times.

The way to overcome this issue is either to use let instead of var- because let has a block scope -or wrap the setTimeout function in another function like so.

Now it is working as expected as demonstrated by the output.

The reason this workaround works is that the function closeCounter closes over the variable counter. This means at each iteration this function gets a new copy of counter- or counter is passed by reference, not by value.

Let us revisit the previous example code — now with a couple of more console.log s

This shows counter has never been garbage collected even though the outermost function has finished running hence closure is happening in full swing.

To sort of recap our discussion of closure,here are the pros and cons

Advantages of Closure.

  • Data hiding and encapsulation: making sure data isn’t mishandled outside the rightful or proper function which does the actual data manipulation. This is called module patterns and an introductory article can be found here.
  • We can use closures to preserve the scope of outer variables in an asynchronous environment.
  • Memoization with closure solution. I highly suggest you watch this video if it piques your interest.

Disadvantage of closure

  • Memory hogging leads to memory leaks and frozen webpages but some browsers do smart garbage collection. A smart collection involves identifying variables that are no longer in active use and erasing them.

If you would prefer watching videos to reading these two are the best ones I could find on Youtube.

Thanks for reading and please feel free to comment.

--

--