function reference vs function call

Hello guys, can someone explain why when we use the method addEventListener in javascript, the function being passed as argument is a function reference and not a function call as below:
const button = document.querySelector("button");

function greet() {
const name = prompt("What is your name?");
const greeting = document.querySelector("#greeting");
greeting.textContent = `Hello ${name}, nice to see you!`;
}

button.addEventListener("click", greet);
const button = document.querySelector("button");

function greet() {
const name = prompt("What is your name?");
const greeting = document.querySelector("#greeting");
greeting.textContent = `Hello ${name}, nice to see you!`;
}

button.addEventListener("click", greet);
7 Replies
Jochem
Jochem2mo ago
you're telling the javascript engine that when button emits the click event, it needs to call something. that's why you're passing the function rather than calling it. If you were to call the function in addEventListener, it would pass the result of the function, which in this case is undefined
Faker
FakerOP2mo ago
yep I see, like even though the button wasn't clicked, the function would have still been executed ?
Jochem
Jochem2mo ago
yes, exactly
Faker
FakerOP2mo ago
yep I see, nice explanation, really appreciate, thanks ! 💯 One thing I didn't understand though, how by keeping the function reference, we can later on invoke the function based on the event listener, like what's happening under the hood with the function reference
Jochem
Jochem2mo ago
it's stored by the javascript engine to be called when the event triggers
Faker
FakerOP2mo ago
yep I see, thanks !
ἔρως
ἔρως2mo ago
you can (and should) name your handlers, if you dont need to use arrow functions if you need to manually trigger the click event, you can do one of 3 things: - call the handler directly, by storing it outside (like your greet function - trigger the event in the element, via a method (for example, .focus or the .submit in a form) - manually fire the event in the dom - the most complicated
Want results from more Discord servers?
Add your server