Closures — A moment of truth (Functional Programming and JavaScript)

The closures in JavaScript is one of most misunderstood concepts for the JavaScript developers. The pitfalls of not understanding closures fully mostly stop or withhold developers from writing bug-free code.

There are many articles available on the internet which focus solely on the context of explaining JavaScript closures and nothing else. These articles do not explain the meaning of the term “closures”. On the contrary, these articles explain closures only from the JavaScript’s standpoint (we will get there in a jiffy). The focus of this article is to explain “closures” not only from the JavaScript standpoint but also from a functional programming standpoint.

A prerequisite for this write-up is a clear understanding of “Lexical Scoping”. Please read about lexical scoping before you proceed with this article.

History of Closures

TLDR; — If you want to directly jump into understanding closures in the pretext of JavaScript, I’d recommend you to skip this section and straightaway go to “Definition of Closures” section.

Before diving into closures, let us first understand another term, lambda, which is used quite interchangeably with closures (which I feel that it shouldn’t be used interchangeably to some extent!!).

According to wikipedia, lamda calculus is,

“Lambda(λ) calculus is Turing complete, that is, it is a universal model of computation that can be used to simulate any Turing machine. Its namesake, the Greek letter lambda (λ), is used in lambda expressions and lambda terms to denote binding a variable in a function.”

For the scope of this discussion, let’s just skip the reference with Turing complete. The important part is to understand the phrase, “ binding a variable in a function”.

Similarly, another common misconception is to compare an anonymous function to a closure.An anonymous function (function literal, lambda abstraction, or lambda expression) is a function definition that is not bound to an identifier(confusing, eh? Let’s discuss more on this). Anonymous function is just a function which doesn’t have a name. A lambda expression can also be defined as an anonymous function a function defined with no name.

Closures, on the other hand, was introduced in the 1960s in order to evaluate the expressions of λ-calculus (explained above). Closures were fully adopted and implemented in a programming language called PAL in order to support functions which were also lexically scoped (similar to JavaScript). Closures are typically used in places where there is a need to return functions from higher order functions. Functional programming languages (for e.g. LISP etc.) use closures extensively. In case of JavaScript, one practical and common usage of closures is in the usage of data hiding (we will see how data hiding works in the JavaScript world with the usage of closures) or in callbacks.

***A REAL GOTCHA MOMENT???

Yes, you had been using closures for many years (we all have used callbacks at some point while writing JS code) and you didn’t know about it!! I also had the same expression when I first learned about closures***

Definition of Closures

I have read a lot of definition of closures. Some definitions were robust, some were lucid and simple. I’ll list a few definitions which I have found to be quite useful and beneficial in my journey to understand closures a year ago (although, I still don’t understand it completely :D)

“A closure is a persistent local variable scope” — A little weird for me as I couldn’t make out anything from this definition on my first attempt.

“A closure is any function which closes over the environment in which it was defined.” — Too simple yet I found it to be quite confusing.

“A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment) “— Better than the previous one.

The definition below is probably the best one-liner explanation of closures. It's probably the easiest to understand as well:

“Closure is when a function “remembers” its lexical scope even when the function is executed outside that lexical scope” — Probably the best definition I’ve found so far.

This definition is provided by one of my favourite teachers of all time, Kyle Simpson. The basic idea behind the backbone or the concept of a closure lies in the understanding of the fact that, closure is a mechanism by which an inner function will have access to the variables defined in its outer function’s lexical scope even after the outer function has returned. This will eventually be clearer if we work through a few examples.

Examples of Closures

Let us look through a few basic examples to understand what exactly a closure stands for. I would recommend to try out the sample codes for better understanding of closures.

This is a very simple illustration of closure. The answers to the Questions (Q1 and Q2) in the code are as follows:

Q1 — The Lexical Scope is getting attached on line 11. This is what closure is all about. It simply attaches the scope of a function (here inner) even if the inner function gets executed inside anotherFunction (oh the irony!!).

Q2 — On calling outer function (on line 14), the output which will be printed is:

The king in the North, Jon Snow

Another example (quite similar to the first kind)to illustrate the working of closures is as follows:

This example is quite similar to the above one, but it requires you to have a basic understanding of closures as well as variable hoisting. I know that “Variable hoisting” is outside the scope of this article so I won’t be going into that in detail.

Q1 — Here the answer will be

Jon Snow, the one true king

Here the inner function is defined before the variable stark but the due to the property of closures, the inner function gets married to the Lexical Scope and hence it has access to the variable defined within that scope (the order of declarations doesn’t matter).

Let us go through another example to understand closures in a better way.

A very popular (mostly popular for interviews and one of my personal favourites) is the following example:

It's pretty obvious as to what you would expect as the output of the above code. Go ahead and try it. I’m sure you would be surprised if you haven’t come across this example before:

value is : 6value is : 6value is : 6value is : 6value is : 6

It's really important to understand what exactly is going on over here. Here the console.log("value is :"+i); statement is written inside the anonymous function of setTimeout(). The setTimeout starts executing after the for-loop gets over, i.e. the “i” variable is already set to 6. In simpler words, by the time setTimeout() starts executing after 1,2,3,4 and 5 seconds, the for-loop has already been executed and the value of “i” has already been incremented to 6. Here there are 5 different setTimeout functions which have the same lexical scope (here it’s the global scope). The global scope has the only one value of variable “i”, which is 6. Hence, we get the above output.

The easiest way to fix this (i.e. make it behave in the desired manner) is to make the following change:

The question that we need to ask ourselves is “how we can have different scopes (not the global scope)for each iteration of the loop” so that the setTimeout methods (there are 5 setTimeout function(s) to be precise).

The easiest way to achieve this is to create an Immediately Invoked Function Expression (IFFE) . Again, explaining IFFE is beyond the scope of this article. In JavaScript, since the functions are the only way to create a lexical scope, its important to wrap the setTimeout method inside a function to give it its own local scope and hence it will have the correct value of variable “i” for all iterations. The output after this modification will be:

value is : 1value is : 2value is : 3value is : 4value is : 5

Practical usages of Closures

One of the primary usages of closures in the real world (which I can think of at the top of my head) is to create an illusionary private data member. The following code illustrates a similar use case:

I have taken this snippet from FreeCodeCamp. Here the inner function, guessPassword has access to the outer function’s password variable, but there is no way to access the variable password from the outside.

Another practical usage of closure, is also a simple case of data hiding, similar to the above one:

The output of the above code will be

Inner function

The above example is pretty similar to the previous example. The only difference here is this example shows another usage of having a function expression instead of an anonymous function as its inner function (which is returned and which encloses the private scope).

Conclusion

I have tried to jot down almost all the important aspects of a closure in the pretext of JavaScript and also a bit of functional programming (just the introduction). Thanks for reading through the entire write-up. Do share your thoughts in the comment section, if you want to discuss on a specific example from the write-up. Again, this is a beginner level article and if you find a better resource, then do share it in the comments section.

--

--