Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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
8,377 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);