Learn Form Validation by Building a Calorie Counter - Step 88

Hi everyone!

I’m wondering why we don’t need to pass a parameter at step 88 in calorieCounter.addEventListener(“submit”, calculateCalories) to the calculateCalories(e) method which expects an Event as the parameter. How does it work without passing a parameter to it, what happens in the backend?

Thanks in advance!

The event listener expects a callback function. If you try to pass a parameter to the function the function will get called before the actual event being listened to even happens.

The event listeners’ job is to invoke the function when needed. So only the reference to it is needed for that.

1 Like

Hmm, I see.
So the calculateCalories method gets its parameter e (which is used to tell the user that its parameter is an “Event”- meaning the parameter can be any character/string(?)) in the backend after being invoked by the event listener? Asking this because of my previous experience with Java - there we couldn’t call a function without “()” and if it has a parameter, without “(parameter”) if I remember correctly.

Yeah the event is being created when the event listener calls the handler.

Recall that we are not actually calling the handler here. Just passing a reference to it. (Think of it like a pointer to the function)

that’s the same in JavaScript. In this case you should not call the function when creating the event listener, you just need to pass a reference to a function to the event listener, you are telling it “call this function when the event you are listening for happens”

Many many thanks to both of you! :handshake:I think I have now understood the logic behind it.

1 Like