1

I am very confused with the difference between called function with/without parentheses in addEventListener().

Code 1:

var clickerNumber = -1; 

var button = document.getElementsByTagName("button")[0];

button.addEventListener("click", clickerCount);

function clickerCount(){
    clickerNumber++;
    console.log(clickerNumber);
}

Code 2:

var clickerNumber = -1; 

var button = document.getElementsByTagName("button")[0];

button.addEventListener("click", clickerCount());

function clickerCount(){
    clickerNumber++;
    console.log(clickerNumber);
}

Code 1 works when I click the button, it will show the clickernumber, but Code 2 only show 0 in the console and clicking the button does not change the clickernumber. what happens here and whats the mechanism in it?

Nyaruko
  • 19
  • 3
  • With `()`, you invoke the function - its code gets run *immediately*, then. Otherwise, you're just passing the function itself, as a callback, which can be called later – CertainPerformance Apr 29 '19 at 04:09
  • 2
    It is the difference between calling the function or passing the function. With () you call the function. When you write `button.addEventListener("click", clickerCount());` you add the value that the function returns, in this case it is `undefined`. So what you are doing is like `button.addEventListener("click", undefined);` You want to pass the function, so it can be called later. That is why you should write `button.addEventListener("click", clickerCount);` – some Apr 29 '19 at 04:13

0 Answers0