Before answering to your question,first lets discuss how your code works :
When you define a function inside another function it creates a clouser.Inside a clouser the inside functions can access the outer functions scope, i mean outer function's variable and argument even if the outer function has returned. In your code the outer function is an immediately-invoked-function .That means it is invoked immediately just after it is defined. When it returns , the inside function is assigned to the onclick event.The click function can access ,as well as modify the outer function's variable (in this case
count
which is defined in the outer function)
even if it returned.
I have commented out in your code.Go through it,it will be clear
First, immediately invoked function (function(){...})()
will invoked immediately.It returns another function.So what is left is a returned function which will be assigned to the onclik handler.
So,after return it will be
var element = document.getElementById('bid');
element.onclick =function(e) { // <- This returned function has becomes the onclick handler
count++; // it can access the outer function's count variable and modify it even if the outer function returns.
if (count === 3) {
// Do something every third time
alert("Third time's the charm!");
//Reset counter
count = 0; // it can also reset outer function's count variable to zero
}
};
How is 'count' value save between invokations? Should not it be reset
every invokation by var = 0?
Right. If you use this code again and again along with immediately invoked function every time count will begin with zero.But you can see the beauty of it if you keep clicking the same button again and again.Even if the outer function has returned ,inner function has access to its variables.So they will get modified every time you click the button
first click to button will print 1,So count is now 1.
second click will modify it again and will print 2 and so on.Remember in clousers inner function can access outer function's variable even if outer function returns.So,inner function doesn't have any count variable.It is just accessing outer scope's variable.So,after third click it will assigned to zero again.
var element = document.getElementById('bid');
var mydiv=document.getElementById('mydiv');
element.onclick = (function() {
// init the count to 0
var count = 0;
return function(e) { // <- This function becomes the onclick handler
count++;
mydiv.innerHTML+=count+'</br>'; // and will retain access to the above `count`
if (count === 3) {
// Do something every third time
mydiv.innerHTML +="Third time's the charm!</br>";
//Reset counter
count = 0;
}
};
})();
<button type="button" id="bid">keep clicking me </button>
<div id='mydiv'></div>