Using a named function doesn't work in an addEventListener

For readability sake, I wanted to declare a function and call it in the addEventListener’s second parameter but that didn’t work. Then, I used an anonymous function and it worked just fine. Why? Here’s my original without an anonymous function:

const checkInputFunc = function () {
  const userInputNum = document.querySelector("#your-guess").value;
  if (!userInputNum) {
    displayInputStatusMessage("Please insert a number");
  } else if (userInputNum > correctNum) {
    displayInputStatusMessage("Too high...");
  } else if (userInputNum < correctNum) {
    displayInputStatusMessage("Too low...");
  } else {
    displayInputStatusMessage("Correct!");
  }
};

document.querySelector("#clickButton").addEventListener("click", checkInputFunc())


And here’s the one with it:

document.querySelector("#clickButton").addEventListener("click", function () {
  const userInputNum = document.querySelector("#your-guess").value;
  if (!userInputNum) {
    displayInputStatusMessage("Please insert a number");
  } else if (userInputNum > correctNum) {
    displayInputStatusMessage("Too high...");
  } else if (userInputNum < correctNum) {
    displayInputStatusMessage("Too low...");
  } else {
    displayInputStatusMessage("Correct!");
  }
});

note that you are giving a function as argument, not calling it - you need to do the same if you write a variable instead of an anonymous function

Hello there,

To add on to what @ILM said:

This line:

document.querySelector("#clickButton").addEventListener("click", checkInputFunc())

Is equivalent to this:

document.querySelector("#clickButton").addEventListener("click", undefined) 

Because checkInputFunc does not return anything, and, therefore, evaluates to undefined

Hope this helps

The second argument (i.e. the name of the function) just needs to be a reference to that function which will be called once the ‘click’ event happens.

document.querySelector("#clickButton").addEventListener("click", checkInputFunc)

If you add the parenthesis after it then the function is called no matter what . That’s what the parenthesis do: they call the function. You only want the function called after the ‘click’ happens…so don’t include the parens. Let the ‘click’ event trigger it.