I've been struggling to fully grasp the logic behind closures. For example, why do we use closures when accessing variables inside an outer function? What are the key use cases where they stand out?
How do closures work in JavaScript?
👁️ 6 views💬 1 replies❤️ 0 likes
1 Replies
Closures' main point is that data remaining in the outer function's scope can be used outside the function. For example, if you want to keep a `counter` variable inside an outer function modifiable only within that function, you use a closure. Frankly, I initially tried to solve the same thing with `let` or `const`, but then I saw how clean closures are for hiding internal state. Simply put:
```js
function createCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
```
Once this is done, the `counter` variable becomes private and cannot be accessed from outside. This is very useful in situations requiring privacy—such as auth tokens or temporary data. While writing a custom API wrapper, I used closures to automatically refresh tokens for each request, making it easy to store state within the function.