A quick note before we start: this post is for beginners trying to understand how closures actually work. I have done my best as per my limited knowledge to explain what happens under the hood, so if I have gotten anything wrong, please correct me in the comments.
When I was first learning closures, I could recite the definition but still could not explain why they actually work. Information that goes past the definition and into the "why" and "How" is sometimes harder to find than expected. One of my dear friends finally explained it to me in a way that made it click, so I thought I should pass it on for any beginner going through the same thing.
The definition we have probably heard: an inner function remembers variables from its outer function, even after the outer function has finished running. That is correct, but it is only the surface. The real question is, what is so special here? Why does that memory survive at all? The answer lives in how the JavaScript engine handles memory behind the scenes.
Here is the example we will use the whole way through:
function counter(n = 0) {






