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
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"
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)
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!
I'm happy I didn't disappoint you.
Thanks!
I'm glad you find it helpful.
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.
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.
The function on its own is not a closure.
Objects are definitely not closures, and methods are functions; which are only part of a closure.
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.
Very first sentence on MDN page:
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.
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.
I see your point, but I think all of this depends on the context and audience.
I think for a beginner audience it's especially important to get the terminology and concepts correct early on - to avoid confusion later.
MDN page now updated to remove the confusing wording 👍
With this definition, any function defined in the global scope is a closure, no ?
Yes, but as I said, the function itself is not the closure. The closure is both things together
Finally, after more than a year. I understood properly what the heck closure. Thanks a lot.
I'm glad you find this helpful.
very simple and to the point thank you
Thanks for your feedback.