JavaScript Asynchronous Programming with JavaScript What is Asynchronous Programming? Examples of Synchronous and Asynchronous Code

Steve Fau
Steve Fau
5,621 Points

why is the callback passed as an arg in btn.addEventListener() without parentheses?

btn.addEventListener('click', carryOn); 

how does the script know when to run the carryOn function?

I've read something about the listener (the 2nd param) being an object to which the Event is passed, but where did we convert our function to an object?

2 Answers

Simon Coates
Simon Coates
4,075 Points

Function is a type of object. So you're able to pass functions around. If you used functionName(), the function would execute immediately. It basically says "when a click event occurs on the btn, here's a function to execute at that time".

Adding a function with parentheses and all that you usually know, is basically "creating a new function on the spot". In the case you posted, the function is already created. Consider this as how we create a function:

function doStuff() { // stuff should be done }

now let's create it without naming, right on click:

document.addEventListener('click', function() { //stuff should be done });

The only difference between the two functions, is that in the later, it's not named doStuff. Since I already have doStuff I may aswell just use it instead of creating another:

document.addEventListener('click', doStuff);