Making Sense Of JavaScript’s Closure With Some Examples

Xiaoyun Yang
Jan 25, 2018 · 4 min read
Photo by Riccardo Annandale on Unsplash

Closure is one of those things in JavaScript that you read a lot about but never fully get. Like with a lot of things in programming, you just need to play around with some examples to fully understand and appreciate the concept.

Instead of explaining to you what closure is, I’m going to show you some examples of how closure is used and walk you through the process of designing your application to take advantage of closure.

Here we go!

What is a Closure?

I like this definition from Secrets of the JavaScript:

A closure is a way to access and manipulate external variables from within a function.

I like to think of a closure as a feature of the programming language to let us do cool things such as:

Object Oriented Programming in JavaScript:

and recursion:

Let’s try a couple of things based on the function we created in the recursion example:

So far so good…

…Uh oh what happened?

Some Observations:

  • can call itself because it maintains a closured reference to itself. This makes recursion possible in JavaScript.
  • also maintains a closured reference to and can read and modify it. The scope of is if you typed this example as-is directly into the browser console.
  • Although is being executed inside of , it didn’t modify the in ’s scope because only recognizes the that was inside of its parent’s scope when it was first created (e.g., ). It doesn’t recognize the inside of the caller, , because it doesn’t maintain a closured reference to its caller’s scope.

Here’s how we can fix so it can leverage the function to modify the inside of its own scope.

The “fix” for seems to work fine but it lends itself to a lot of duplicate code. What if we have to increment variables inside of other functions? It’s not good practice to copy-paste the same function/code into multiple places. Let’s refactor our function using partial application:

The refactored function does not read or modify anything outside of its own scope so it’s a pure function, which illustrates a core principle of functional programming. You call the function as follows: , which reads “increment until starting from ”.

A really nice thing about partial application is that we can partially evaluate the final solution by providing our function a subset of the arguments it needs. Then we can save the intermediate solution to a variable so we can save ourselves some processing time by eliminating the need to evaluate the same intermediate solution every time we call the function to do similar things (assuming your programming language supports this kind of optimization).

Here’s what I mean by that in code:

What’s happening in the code above is that you created a closure to keep the value passed to the function even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure.

The above code is equivalent to the following in ES6:

var multThenAdd = num => mul => add => num * mul + add

Quite elegant but the syntax could seem really strange for someone coming from an imperative language background.

Now you’ve seen partial application in action, here’s a high level discussion on the concept of partial application (also called currying by some).

Partial application is basically a design pattern where your function returns another function that takes an argument. For example, you can call your function like this: , which is equivalent to:

const myFun2 = myFun(arg1)
myFun2(arg2)

Partial application is a powerful design pattern because you can continuing chaining things like What’s happening here is akin to an assembly line in a factory: One argument at a time is applied to to evaluate a better and better partial solution until all the arguments are applied to provide a complete solution.

Here’s an actual piece of code I wrote for a Node/Express app that uses the partial application pattern:

I hope this helped some of you get a better handle on JavaScript and closure.

Thanks for reading! If you enjoyed this article, please check out the other articles that I’ve written on JavaScript:

Here are some resources that that inspired me to create the content of this article:

DailyJS

JavaScript news and opinion.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store