Javascript: Closures.

Alyssa E Easterly
2 min readMar 5, 2021

--

In my quest to strengthen my Javascript knowledge. I have arrived at closures. Let’s talk closures! It’s a part of the basic and integral makeup of Javascript, a functional programming language

Why be aware of what a closure is?

To all you jobseekers/interviewers out there with Javascript in your pocket, it is likely one of the most asked topics in an interview. So listen up!

What is a closure?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state.

We see in this example a closure in action: it is giving us access to the outer function’s scope from the inner function.

Closures hold on to information from when the function was first called, this allows us to reference information held in the outer function, inside our inner function. See in the above photo, the inner findBreed() function can reference the outer value of breed, passed into the outer function freeTheDogs(breed) on the initial declaration.

Boiled down to its basics, a closure is when an inner function has access to its outer functions information.

Why do we use closure?

We have a problem we need to solve in Javascript and we try to solve it with closure. With that begin said, let’s talk about lexical scoping. Lexical scoping is something specific to Javascript, it refers to the variables outside of your scope that are automatically available inside your current function’s scope.

Here’s a look at how Lexical Scoping plays out:

In conclusion, closures are important because ultimately they denote what is and isn’t in scope in a function and what information can be returned from the function itself. I urge you to try creating similar coding examples to the functions you see in this blog. Coding out the functions yourself will be step one in getting a full feel for what closures are!

For more reference and/or you want to pound the pavement of closure knowledge further I’d recommend checking out this helpful closure youtube video.

--

--

No responses yet