How Do Closures Work?
About 1 min
How Do Closures Work? 관련
The JavaScript Interview Prep Handbook – Essential Topics to Know + Code Examples
JavaScript is a widely used language in web development and powers interactive features of virtually every website out there. JavaScript makes it possible to create dynamic web pages and is very versatile. JavaScript remains one of the most in-demand programming languages in 2024. Many companies are looking for proficiency in...
The JavaScript Interview Prep Handbook – Essential Topics to Know + Code Examples
JavaScript is a widely used language in web development and powers interactive features of virtually every website out there. JavaScript makes it possible to create dynamic web pages and is very versatile. JavaScript remains one of the most in-demand programming languages in 2024. Many companies are looking for proficiency in...
Closures are an important concept in JavaScript. When you have a function inside another function, the inner function has access to all the variables of the outer function.
But when this inner function is returned by the outer function, the inner function can be called anywhere outside the outer function and it can still access those variables.
function fun() {
let count = 0;
return () => {
count++;
console.log(count);
};
}
const innerFun = fun();
innerFun(); // prints 1
innerFun(); // prints 2
innerFun(); // prints 3
Here, fun()
declares and initializes a variable count
. Then, it returns an inner function that increments count
before printing it. Now, when you call innerFun()
anywhere outside the fun()
method, it can still access count
and increment it.
This is the concept of closures. You can understand more about closures in the following post by Matías Hernández.