I'm still a beginner in learning javascript. Recently, I learned about IIFE, and there's an example that I could not figure out why there's a difference in results between the following two,
**First one (the callback function is IIFE)- **
button.addEventListener('click', (function() {
let count = 0;
return function() {
count += 1;
if (count === 2) {
alert('This alert appears every other press!');
count = 0;
}
};
})());
**Second one- **
button.addEventListener('click', function() {
let count = 0;
return function() {
count += 1;
if (count === 2) {
alert('This alert appears every other press!');
count = 0;
}
};
});
So, apparently, for the first one, when I click on the button, the alert will come up every other press. As for the second one, the alert will never show up, because the variable "count" will never reach 2.
I just cannot figure out how and why does this kind of behavior happen, and I don't understand the difference between IIFE being a callback function in EventListener and a regular function being a callback in EventListener.
Thanks!