Member-only story

Utilizing JavaScript Closures

Jacob Lozano
2 min readDec 22, 2020

--

JavaScript closures allow JS to emulate object-oriented languages without the use of frameworks or packages. Closures aren’t exactly intuitive, but what they lack in readability, they make up for in functionality, for lack of a better term.

To start off with, closures are formed by functions. A closure is defined by MDN as

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.

Well that sounds like scope with extra steps, so what’s the difference?

A big reason closures aren’t as intuitive for those already familiar with JS is that closures are created upon definition. While they are similar to scopes, this is the big difference between the two, as scopes are created upon execution.

For instance in this function:

var x = 'x';
function functionA() {
var y = 'y'

function functionB() {
var z = 'z'
console.log(x, y, z);
}

functionB(); // prints x, y, z
x = 1;
functionB(); // prints 1, y, z
}
functionA();

We can see that when we eventually hit funcitonB the first time, we print

x, y, z

while the second time, we print

1, y, z

This is because even though x=1 happens after functionB is defined, the closure does not disappear…

--

--

No responses yet

Write a response