0

I don't understand why a callback function defined with () is only executed immediately and never again. For instance:

<body>
    <button type="button">Click Me!</button>

    <script>
      const buttonElement = document.querySelector('button');
      function sayHello(e){
          console.log("hello")
      }
      buttonElement.addEventListener('click', sayHello());  // function sayHello will be executed imidiately only once
      buttonElement.addEventListener('click', sayHello);    // function sayHello will be executed only when button is clicked

    </script>
</body>

Why does the first EventListener will be executed immediately and never work again ?

Caladay
  • 111
  • 6
  • Because the `()` is the syntax to "call" the function. Whereas without the `()` affixed, it then refers to the function object itself. For demo, run this `console.log( sayHello )` .. you'll see the function definition. – GetSet Mar 07 '22 at 20:03
  • 1
    In this context, `sayHello` is the function itself, and `sayHello()` is what the function returns. – James Mar 07 '22 at 20:28

0 Answers0