Javascript Closures, Put Simply

Kelsey Creehan
2 min readJan 26, 2021
A pattern of many lightbulbs covering the photo

Closure is a programming technique, that (much like recursion) is often over-complicated and can cause unnecessary headaches. However, don’t let the intimidating lexical syntax scare you away. You can start down the closures internet rabbit hole soon (trust me, there’s enough to keep you busy for a few weeks), but first, let’s grasp the basic concept.

To understand closures, we first need to talk about scope. Scope determines the accessibility of functions or variables. Just like a Javascript file is its own scope, a function has its own scope. A new scope is created with each new function. Anything defined inside of a function is not accessible from outside, but variables created in the global scope outside of the function are accessible from the inside.

At its simplest, a closure is a function that returns another function. However, there is a bit more nuance to it — the inner function’s utilization of something that’s been defined in the outer scope. The inner function is a local variable to the outer function. When a function is defined inside of another function, the inner function has access to the variables and scope of the outer function. Closure occurs when an inner scope accesses the outer scope once the outer scope is done executing. The inner function “closes over” the scope of the outer function, thus creating a closure.

To put it metaphorically, think of the outer, or parent, function as a “pregnant” function, and within, there’s an inner “pregnant” function that returns a baby. When that outer function is invoked, the baby is born. Say that the baby object holds attributes for eye color or hair color. The eye color could be passed in as an argument to the parent function, and the hair color could be passed into the baby function as an argument. Either way, the baby function would have access to those parameters.

A baby’s feet
If only all functions were this cute…

Now for a more tangible, real-life example. We’re working on a racing app. Every time a racer crosses the finish line, they receive a message — either that they’re the winner, or they lost. The message displayed ultimately depends on the order of the individual racer’s finish — we want the first to finish to receive the winning message, and then all the rest get the losers’ notification. We can use a closure to accomplish that!

Try this out for yourself to see the results!

Hopefully this has helped deepen your understanding of closures. Thanks for reading.

--

--