What is a Closure?

Andrew Rivera
3 min readMar 18, 2019

--

An interview Question

“What is a Closure?” I was recently asked this in an interview. I knew the basic idea of what Closures are. They are a feature in Javascript that allows functions to remember the variables from when the function was called. A closure provides a snapshot of the scope chain from when the function is called. I explained these points to my interviewer. He nodded in agreement, and asked me a follow-up question, “Why are closures important?” I didn’t have an answer for that. I didn’t know at that moment, but I was going to find out (and share my findings with all of you!). Let’s get started!

A Refresher on Closures

According to Mozilla’s Developer Network, a closure is defined as:

The combination of a function and the lexical environment within which that function was declared.

Let’s see if we can explain it easier terms to understand…

Try to think of functions as values, and these values have some attributes:

  • The code in the body of the function.
  • The environment in which they were created.
source: https://lostechies.com/

When a function is declared the function definition is being stored as well as all the variables, and other function values at the time of creation. A closure is essentially taking a snapshot of the environment(or scope) that exists at the creation of the function.

Let’s look at a simple example, an excerpt of “Eloquent Javascript” by Marijn Haverbeke.

function wrapValue(n) {       
let local = n;
return () => local;
}
let wrap1 = wrapValue(1);
let wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
Excerpt From: Marijn Haverbeke. “Eloquent JavaScript.” iBooks.
  1. We define a function called wrapValue that takes an argument of n.
  2. wrapValue encloses a local variable, that is equal to the argument passed in.
  3. wrapValue returns a function that returns the local variable.

. The inner function will have access to all of its outer scopes. Look at what happens when we call the functions and save them to variables. Every time the function is called, a new local variable is created. Each instance of the function has its own local variable from when it was created. We don’t have to worry about other function calls changing the local variable in the function.

Why Are Closures Important

So now that we have an understanding of what a closure is, let’s discuss why they are important and what we can do with them.

Protecting Variables and Privacy

When you enclose a variable inside of the outer function you protect it from being accessed and potentially rewritten by any other parts of your program with the exception of the inner functions, these functions are also known as privileged methods. Imagine if you had multiple functions that needed to access a counter. It would be dangerous to put the counter in the global scope of your program. but if we wrote our functions to include the counters in their closures we can prevent messing up our counters. Take a look at this example from the MDN web docs:

const counter = (function() {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();

console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1

The methods inside the scope of the counter variable give us access to the counter, keeping it private from the global scope.

Keep those variables private

Conclusion

In conclusion, we got to review what a closure is and how we can use it to keep variables protected and private from other functions. Learning is an ongoing affair for me, so if you know of some other common uses for closures please feel free to leave a comment!

--

--

Andrew Rivera

Living life on my own terms. The coding experiments, projects, and search for computer science clarity from a Musician turned Web Developer.