Probably this is one of the most dreaded topics to talk about. Quite a few readers won't even bother to read on but hey! hang in there and we will keep things simple. To explain what closures are, I won't begin with the classic ubiquitous example of a silly function within another function (keeping it for later though). Well, closures also play a very obvious role when implementing event handlers (DOM Level 2). Lets talk with an example, shall we?
There's nothing much to the code shown above, its as simple as a function that takes in an integer and sets event listeners on two different buttons. The first event listener calls a function (callback) when the first button is clicked. The callback function in turn increments the counter and shows it in an alert box. The second event handler does nothing different apart from the fact that its callback function decrements the same counter. Do we understand that even after the function setClickHandler has finished execution (offboarded from the execution stack with all its variables and arguments), the two event listeners are actively listening for a click on their respective buttons? Well, that's how event listeners work, right? You set them up once and they stay there for you unless you call "removeEventListener" on the node. There's another interesting thing to observe in the small code snippet. When the function "setClickHandler" has already left the call stack (no arguments and local variables in memory anymore), why do the callback functions not throw a "ReferenceError" when trying to access the argument "counter" which effectively lies in the lexical scope of "setClickHandler" ? Well, if you want to attribute this to the scope chain, you won't be completely wrong but then when I ask you how does something up in the scope chain remain active in memory after the owner function has offboarded the execution stack? That's when you need to say CLOSURES.
If you try to inspect such a function's execution in devtools, you shall notice that as soon as the function is pushed on the top of the execution stack, its closure shows up in the scope chain as if the function carried it throughout. If you're 5, a closure is a function who took notes ( [[Environent]] ) to remember what has been taught in the school, outside the school.
If you really want to visualize this, the easiest way is to use an online visualizer. I will keep it simple and use chrome devtools instead.
Inner function returned from the Outer funtion
It's not necessary that the inner function be returned to form a closure
Chrome does not show the inner function in the Local scope?