0

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!

JJJJAA
  • 1

1 Answers1

0

The difference is that in the first code block, the outer function is being called immediately, and returning the inner function, which is then used as the event listener. In your second example, the outer function is used as the event listener, so it isn't called until/unless the event is triggered, and it doesn't do anything but create a function that it returns (which is then ignored).

It may help to pull things apart a bit. Here's a slightly-modified version of the first example, but without using an IIFE:

function createListener() {
    let count = 0;
    return function () {
        count += 1;

        if (count === 2) {
            alert("This alert appears every other press!");
            count = 0;
        }
    };
}
const listener = createListener();
button.addEventListener("click", listener);

The only difference is that in the version in the question, createListener is temporary and unnammed, and there's no listener variable.

Here are some other questions whose answers may be useful:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for the explanation. So what you mean is that in the first one, the returned function will become the callback function of the button's eventlistener, right? – JJJJAA Dec 28 '22 at 10:59
  • @JJJJAA - Right. The outer function is called immediately (as you say, it's an IIFE), and it returns the inner function; then that is used as the event listener. – T.J. Crowder Dec 28 '22 at 11:14