You are on page 1of 1

Sign in Get started

LEARN WEB DEVELOPMENT WEB DEV COURSES WRITE FOR US


codeburst
Bursts of code to power

Understand Closures in
through your day.

Follow

JavaScript
1.6K 20 Closures don’t have to be complicated. Learn and understand the
basics of closures in just 10 minutes.

Brandon Morelli Follow

Jul 24, 2017 · 5 min read

Open and Closure. Photo via unsplash.com

What’s a closure?
Closures are a key aspect of JavaScript that every developer should know
about and understand. Today’s article merely skims the surface of closures,
but will give you a good idea of what closures are and how they work in
JavaScript. Lets jump in…

We’ll start by taking a peek at two textbook definitions of closure.

Definition #1:

A closure is a function that has access to the parent scope, even after the scope
has closed.

Definition #2:

A closure is the combination of a function and the lexical environment within


which that function was declared.

Great. But what do those actually mean?

First you need to understand scope in JavaScript. Scope is essentially the


lifespan of a variable in JavaScript. You see, where a variable is defined plays
a large role in how long that variable is around, and which functions in your
program have access to it.

Lets look at an example.

When you create a function in JavaScript, it has access to variables created


inside and outside the function.

Variables created inside a function are locally defined variables. A local


variable can only be accessed within the function (scope) that it is defined
in. In the example below, you’ll see that if we try to log the value of words

outside of the function we get a reference error. That’s because words is a


locally scoped variable:

1 // Example of accessing variables INSIDE the function


2 // words is a LOCAL variable
3 function speak(){
4 var words = 'hi';
5 console.log(words);
6 }
7 speak(); // 'hi'
8 console.log(words); // Uncaught ReferenceError: words is not defined

speak.js hosted with ❤ by GitHub view raw

Contrast that to this example where we define words in the global scope.
This means it’s accessible to every function in the document:

1 // Example of accessing variables OUTSIDE the function


2 // words is a GLOBAL variable
3 var words = 'hi';
4 function speak(){
5 console.log(words);
6 }
7 speak(); // 'hi'
8 console.log(words); // 'hi'

speak.js hosted with ❤ by GitHub view raw

Nested Functions
What happens when we nest one function inside of another? I want you to
follow along with this next example because this is where it gets fun!

If you’re using Google Chrome, open up your developer console with


[WINDOWS]: Ctrl + Shift + J [MAC]: Cmd + Opt + J

Cool. Now copy and paste the below code into your console. All we’ve done
is create a function named speak . speak returns a function named logIt .

And finally all logIt does is log the value of words to the console, in this
case that means it logs 'hi' to the console.

1 function speak() {
2 return function logIt() {
3 var words = 'hi';
4 console.log(words);
5 }
6 }

closure.js hosted with ❤ by GitHub view raw

Once you’ve got that copied into your console, we’re going to create a
variable and assign it to our speak function as so:

var sayHello = speak();

Now we can see what the value of sayHello is by calling the variable but not
invoking the inner function:

sayHello;

// function logIt() {
// var words = 'hi';
// console.log(words);
// }

As expected, sayHello is referencing our returned inner function. This


means that if we run sayHello() in the console, it will invoke and run the
logIt() function:

sayHello();
// 'hi'

It works! But this isn’t anything special. Let’s move one line of code and see
what changes. Take a look at the example below. We’ve moved our
declaration of the variable words outside of the inner function and into the
speak() function:

1 function speak() {
2 var words = 'hi';
3 return function logIt() {
4 console.log(words);
5 }
6 }

speak.js hosted with ❤ by GitHub view raw

Like before, lets declare a variable and assign it to our speak function:

var sayHello = speak();

Now we’ll take a look at what our sayHello variable is referencing:

sayHello

// function logIt() {
// console.log(words);
// }

Uh oh. There’s no words variable definition. So what’s going to happen


when we invoke the function?

sayHello();
// 'hi'

It still works! And that’s because you’ve just experienced the effects of a
closure!

Confused? That’s ok. Think back to our closure definition:

A closure is a function that has access to the parent scope, even after the scope
has closed.

In this case our speak() function’s scope has closed. This means the var

words = 'hi' should also be gone. However, in JavaScript we have this cool
little concept called closures: Our inner function maintains a reference to Top highlight

the scope in which it was created. This allows the logIt() function to still
access the words variable — even after speak() has closed.

1 function speak() {
2 var words = 'hi';
3 return function logIt() {
4 console.log(words);
5 }
6 }

speak.js hosted with ❤ by GitHub view raw

It’s important to note that every function in JavaScript has a closure. There’s
nothing you need to explicitly do to a function to get this to work. It’s just a
part of JavaScript.

Example #2
Lets examine another example. This one is a little more complex. Here’s the
code:

We’ve got a function name that takes one parameter and returns an
anonymous function that takes a different parameter. The result of the
inner function returns a string.

Let’s create two invocations of the name function. For one we’ll pass in the
name John, and the other, Cindy:

var j = name('John');
var c = name('Cindy');

Lets see exactly what j is referencing now:

j;

// function (a) {
// return `${n} likes ${a}`;
// }

Awesome. So we know from our previous example that because of closures,


the function should still be able to access the n variable from the parent
scope. All we need to do is pass in the value of a when invoking our
function.

Lets try it out:

j('dogs'); // 'John likes dogs'


c('cats'); // 'Cindy likes cats'

It works! Because of closures we’re able to successfully execute our


functions that reference variables from a previously closed scope.

Want more advanced JavaScript?


Check out: JavaScript: Understanding the Weird Parts

Closing Notes
Hopefully you can now understand the basics of closures is in JavaScript
and how they work! This is merely the tip of the iceberg though. You now
have the knowledge to learn about the more complex and practical
examples of closures.

I publish a few articles and tutorials each week, please consider entering
your email here if you’d like to be added to my once-weekly email list.

Check out my recent articles:


How I built an Interactive 30-Day Bitcoin Price Graph with React, SVG,
and an API

The 3 Best React JS Courses on the internet.

And when you’re ready to really dive into web development, check out
my Best Courses for Learning Full Stack Web Development

If this post was helpful, please click the clap 👏button below a few
times to show your support! ⬇⬇

JavaScript Web Development Technology Tech Programming

1.6K 20

WRITTEN BY

Brandon Morelli Follow

Creator of @codeburstio — Frequently posting web


development tutorials & articles. Follow me on Twitter too:
@BrandonMorelli

codeburst Follow

Bursts of code to power through your day. Web Development


articles, tutorials, and news.

More From Medium

Vue with Nuxt.js — show How to make Drag and some things you should Touchpoints - Safe,
GET URL query drop in NativeScript be known as a javascript Secure Integrations
parameters in view Raj Bhatt in ashutec
developer Everywhere!
template or script ( #Nuxt Md Shoharab Pk James Andrew Vaughn in
#Vue ) MindTouch Product and
Yuma Inaura いなうらゆうま 稲 Engineering
浦悠馬 @yumainaura

Dark Mode in React with Drawing rectangle on Sending Email With Preparing to Learn
localStorage video using canvas and Firebase Functions JavaScript
Thomas Weld in The Startup
FabicJs [Firestore & HTTP Aidan McBride
Deepak Rai
Triggers]
Raja Tamil

Learn more. Make Medium yours. Write a story on Medium.


Medium is an open platform where 170 million readers come Follow the writers, publications, and topics that matter to you, If you have a story to tell, knowledge to share, or a
to find insightful and dynamic thinking. Here, expert and and you’ll see them on your homepage and in your inbox. perspective to offer — welcome home. It’s easy and free to
undiscovered voices alike dive into the heart of any topic and Explore post your thinking on any topic. Start a blog
bring new ideas to the surface. Learn more

About Write Help Legal

You might also like