Getting Closure with JS

Closures are something in JavaScript that took me a second to wrap my head around, and it’s something I hear come up frequently with my peers so let's talk about what they are and how they work.

According to Mozilla docs, “A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.”

To explain this a bit, let's look at lexical scope.

function outerFunc() {
const name = 'Jake'; // name is a local variable created by outerFunc
function innerFunc() { // displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
innerFunc();
}
outerFunc();

In the above code, we have an outer function that defines a variable name, which the inner function has access to and references when that outer function is invoked. Now let’s take a look at a similar line of code.

function outerFunc() {
const name = 'Jake'
function innerFunc() {
console.log(name)
}
return innerFunc;
}
var logName = outerFunc();
logName()

This code runs exactly the same as the previous code. The reason we are able to return innerFunc before it is invoked is because of the closure that was formed. How it works is that logName is a reference to the instance of innerFunc that is created when outerFunc is invoked. It’s ok if you need to reread that last sentence a few times. The instance of innerFunc is still able to keep the variable name in its lexical scope. So when logName is invoked, the name “Jake” is still available to be read.

This concept was introduced to me at Flatiron School using this next line of code, and it’s a great example of why closures can be confusing.

function baseNum(x) {
return function(y) {
return x * y;
};
}
var doubleOf = baseNum(2); // x = 2
var tripleOf = baseNum(3); // x = 3
console.log(doubleOf(10)); // y = 10, console displays 20
console.log(tripleOf(4)); // y = 4, console displays 12

We write a function that takes in a single argument and returns another function that also takes a single argument. The functions doubleOf and tripleOf are both closures. They share the same functionality but store different lexical variables. In doubleOf's, x is 2, and in tripleOf, x is 3. We then pass in new arguments to these new functions, which act as the y defined in the baseNum function.

I hope this was helpful!

California native, living in NYC. Early Career Software Engineer.