2Minutes: JavaScript Closures
What is JavaScript Closures
Let’s have a look at the following code:
function countdown(start) {
let counter = start;
return () => counter--;
}
const count = countdown(10);
console.log(count()); // 10
console.log(count()); // 9countdown() is a function that returns another function that has access to a variable from the outer scope. That probably sounds like Greek, I know, so let’s take it step by step.
We have three scopes here (what’s scope? We’ll talk about it in another post): the global scope (the entire file), the countdown() scope, and the returned function’s scope.
Within the countdown() scope, we have the counter variable. It’s not accessible anywhere outside countdown(). However, since the returned function is created inside countdown(), it has access to the counter variable.
The expression const count = countdown(10) returns a function and stores it in count. Now, according to how the returned function is implemented, every time count() is called, it returns the current value of counter and then decrements it.
And here’s the magic of JavaScript: the countdown() function has already finished executing, yet the returned function can still access and update its local variable. That’s a closure !
Closures are used everywhere in JavaScript, even if you don’t realize it. Things like event listeners, timers, React Hooks, and private variables all rely on closures, so it’s definitely worth digging deeper after this article.
That’s 2Minutes Concept, see you in the next one !
Sources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
https://www.geeksforgeeks.org/javascript/closure-in-javascript
https://www.freecodecamp.org/news/closures-in-javascript-explained-with-examples