Not fully understanding how this closure works <p>I have an excerpt from <a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">How do JavaScript closures work?</a></p> <p>I am having a difficult time understanding closures. </p> <pre><code> &lt;button type="button" id="bid"&gt;Click Me!&lt;/button&gt; &lt;script&gt; var element = document.getElementById('bid'); element.onclick = (function() { // init the count to 0 var count = 0; return function(e) { // &lt;- This function becomes the onclick handler count++; // and will retain access to the above `count` if (count === 3) { // Do something every third time alert("Third time's the charm!"); //Reset counter count = 0; } }; })(); </code></pre> <p>How is the 'count' value saved between invocations? Should not it be reset every invocation by var = 0? </p>