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:
7 Replies
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
yep I see, like even though the button wasn't clicked, the function would have still been executed ?
yes, exactly
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
it's stored by the javascript engine to be called when the event triggers
yep I see, thanks !
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