DEV Community

Cover image for Closures in JavaScript - the Simplest Explanation
Sam
Sam

Posted on • Originally published at blog.dotenx.com

Closures in JavaScript - the Simplest Explanation

Closures in JavaScript are like secret passageways for a function to remember certain variables, even after it's done running. In this article, I'll try to answer the question "how do JavaScript closures work?" in the simplest way so you can start using them right away.

Before we move on, remember you can unlock the full potential of your website development by using DoTenX, an open-source platform that allows you to create professional-grade websites, landing pages, APIs, and more. Take advantage of DoTenX's powerful tools and capabilities by visiting the repository at github.com/dotenx/dotenx today!


Let's say you want to create a simple counter, but you don't want other parts of your code to mess with the counter's internal number. You can create a function that returns an object with methods that can change the internal number, but only the function knows about it. Here's an example:

function counter() {
  let count = 0;

  return {
    increment: function() {
      count++;
    },
    decrement: function() {
      count--;
    },
    getCount: function() {
      return count;
    }
  };
}

let myCounter = counter();
console.log(myCounter.getCount()); // 0
myCounter.increment();
console.log(myCounter.getCount()); // 1
Enter fullscreen mode Exit fullscreen mode

In our example, you could say the counter function returns an object with three methods: increment, decrement, and getCount.

Each of these methods have access to the count variable, which is defined within the parent counter function. But, because the counter function has completed execution, the count variable is not directly accessible from the global scope while the inner functions still have access to it.

In other words, the returned object and its methods are closures that have access to the count variable.

So, this was one of the common use cases of closures and now let's take a look at another example.

Another common use case for closures is to create a function that we want to pass as a callback and maintain access to variables in its parent scope. For example, take a look at this code:

function createFullName(firstName) {
  return function(lastName) {
    return firstName + " " + lastName;
  };
}

let myFullName = createFullName("John");
console.log(myFullName("Doe")); // "John Doe"
console.log(myFullName("Smith")); // "John Smith"
Enter fullscreen mode Exit fullscreen mode

In this overly simplified example, we have a function createFullName that takes a person's first name as an argument and returns a new function which itself takes a person's last name as an argument and returns the full name.

The inner function is a closure because it "closes over" the firstName variable and remembers it, even though the parent function has finished running. This can be useful for example in a form where user fills first name and last name in two different inputs.

This technique is also one of the fundamentals of functional programming in JavaScript.

Can you add any other use cases or examples?

Top comments (19)

Collapse
 
the_yamiteru profile image
Yamiteru

At first I though this article is gonna be a disaster (plainly based on my experience with such articles). But I've been delightfully proven wrong. It's a very nice introduction for beginners.

Good job!

Collapse
 
mohsenkamrani profile image
Sam

I'm happy I didn't disappoint you.
Thanks!

Collapse
 
mohsenkamrani profile image
Sam

I'm glad you find it helpful.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Not really quite correct. A closure is the combination of a function and the scope in which it was defined. I think that's probably about the simplest way to put it.

Collapse
 
mohsenkamrani profile image
Sam

Not sure which part is not correct.

Also, I didn't provide any definition against this (function and its lexical environment), indeed I didn't even talk about the definition.
I just wanted to show the concept with two of the most common use cases by example. Sometimes I find the definition more confusing than just seeing the concept in action.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The inner function is a closure...

The function on its own is not a closure.

...the returned object and its methods are closures...

Objects are definitely not closures, and methods are functions; which are only part of a closure.

Thread Thread
 
mohsenkamrani profile image
Sam

Not right. Take a look at MDN and this section in particular:
"...add5 and add10 are both closures."

This is idiomatic enough for me and I'm fine with it and I guess MDN is too.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Very first sentence on MDN page:

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

They seem to get a little loose with the wording further on. Semantics really, but I think it's an important thing to help avoid confusion when talking about closures and functions. Regardless, saying an object is a closure is definitely not correct.

Overall, probably better to say that a function 'forms' a closure rather than 'is' a closure - keeps the distinction.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Looking more at the MDN page, they mostly say 'form' instead of 'is' - I've made a PR via GitHub with a few tweaks to the page. MDN is a superb resource - mostly because it's community maintained like Wikipedia.

Thread Thread
 
mohsenkamrani profile image
Sam

I see your point, but I think all of this depends on the context and audience.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

I think for a beginner audience it's especially important to get the terminology and concepts correct early on - to avoid confusion later.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

MDN page now updated to remove the confusing wording 👍

Collapse
 
calag4n profile image
calag4n

With this definition, any function defined in the global scope is a closure, no ?

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yes, but as I said, the function itself is not the closure. The closure is both things together

Collapse
 
wrench1815 profile image
Hardeep Kumar

Finally, after more than a year. I understood properly what the heck closure. Thanks a lot.

Collapse
 
mohsenkamrani profile image
Sam

I'm glad you find this helpful.

Collapse
 
nourhan51964568 profile image
NourhanAhmed

very simple and to the point thank you

Collapse
 
mohsenkamrani profile image
Sam

Thanks for your feedback.