Understanding Closures

Joy Evans
2 min readAug 3, 2021
Photo by Florida-Guidebook.com on Unsplash

Starting to learn a new programming language can start exciting but can also quickly become frustrating. JavaScript has thrown me into that exact situation. Since graduating from Flatiron School, I have had an opportunity to spend more time driving into topics that baffled me during my time in boot camp and want to take this time to help others that may be struggling with grasping certain topics and what better way to gain a better understanding about something than to write about it.

When I was first introduced to the world of JavaScript, I don’t even recall hearing the term “closures.” Just trying to deal with functions was enough trouble for me at the time. Thank goodness for MDN!

So let’s start by defining what a closure even is.

A closure is the combination of a function and the lexical environment within which that function was declared.

And the benefit of using them is as follows:

Using closures in this way provides benefits that are normally associated with object-oriented programming. In particular, data hiding and encapsulation.

If we break down this definition, we’re looking at a simple function like so:

function tvShow() {return "Dexter";}tvShow()

Now we’ll take that function and add a variable, and then nest them within another function (an outer function).

function tvShow() {let name = "Dexter";function displayName() {console.log(name);}displayName();}

This example includes an outer function called tvShow , an inner function called displayName and a local variable called name. The inner function has clear access to any variables within the outer function, but the inner function itself is off-limits to anything outside the outer function. It reminds me of asking a neighbor for a cup of sugar or whatever else you need: the neighbor is the outer function, and the sugar can either be seen as a variable or inner function. Either way, you can’t access it without going through the neighbor.

… closures are created every time that a function is even created. So when currentBinge is invoked, the variable name is accessed, and “Dexter” is passed, as shown below.

function tvShow() {let name = "Dexter";function displayName() {console.log(name);}return displayName();}let currentBinge = tvShow();currentBinge;

Feel free and comment, share and check out some of the resources posted below. Thanks for reading!

--

--

Joy Evans

Software Engineer | C# | Angular | Ruby on Rails | Javascript | React