How do Closures work in JavaScript? Explain with a simple example
Hello everyone! I just started learning JavaScript and I can't understand the topic of closures. I read different articles, but I'm still confused.
For example, there is this code:
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const myCounter = counter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3
Why doesn't the count variable reset each time? After all, the counter() function has already finished its work, but we can still change its internal variable. I expected that after the first call to myCounter(), the count variable would be destroyed since it was declared inside the function.
And another question: why are closures needed at all? In what real situations are they