Photo by Sonam/karehop via Getty Images

Let’s dig into the definition of a closure and explore some examples.

MDN defines a closure as “the combination of a function and the lexical environment within which that function was declared.” Great..but can we simplify even more into layman’s terms?

Think of a closure as a function with preserved data. The preserved data consists of any variables or arguments that were in scope at the time of function call. Each and every function call creates its own preserved data which we call a local binding. The idea that we can access a particular instance of a local binding is closure.

Let’s look at some examples:

The code below shows an outer and inner function. The outer function takes in a number, assigns it to a local variable (local) and returns our inner function. The inner function computes and returns the value of the local variable multiplied by two.

simple outer/inner function example of closure

demonstrates multiple local bindings (closures)

As mentioned earlier, each time a function is called a new local binding is created. Therefore a single function can have various local bindings as illustrated in the code above. We have a closure which accesses the binding of num = 2 and a closure which accesses the binding of num = 4. We also get the ability to call var1() and var2() anywhere in our program and they’ll maintain their local bindings.

The next example is a tad more complex. It considers both an outer and inner function, but this time the inner function takes in an argument. The objective of this code is to build a DRY function that creates a blueprint for multiplication. We can bind this function to a factor (ex: 5) and then reuse over and over again passing in different numbers.

more complex outer/inner function example of closure

functions see the bindings in which it was created, not called

Above we are creating two separate environments on lines 7 and 10. tripleconstructs an environment where factor = 3 and quadruple does the same where factor = 4. Now looking at line 13, the function which is returned by calling triple(5) recalls that factor = 3 and recognizes that the argument of 5 represents num. So, the result of num * factor is returned.

I hope this article helped to provide some more explanation around what a closure is. Feel free to comment below with feedback, examples of when you’ve used closure, or any additional tips!

Previous articleUsing Python to Scrape the Meet-Up API


Please enter your comment!
Please enter your name here