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 Asynchronous JavaScript with Callbacks Async Programming and Callback Functions

Why couldn't we just put getJSON as a callback reference in the addEventListener method?

.

2 Answers

highlandcow
highlandcow
7,352 Points

I actually got hung up on this question myself and couldn't come up with a good explanation other than "addEventListener expects a function declaration rather than a function invocation" which is either a gross oversimplification or plainly wrong (but conveniently gets me to the next video). Hoping someone in the community can chime in with a good explanation, perhaps with a simple example. Thanks!

highlandcow
highlandcow
7,352 Points

I reviewed the "Callback Functions in JavaScript" course. Someone touched on this topic in the discussion on one of the videos: "When you put parentheses after a function name (with or without arguments), you are invoking ("calling") the function immediately and passing the function's return value as the argument. But for a callback, you want to pass the function itself, so it's important to not use the parentheses." Helped clear this up for me.

Farid Lavizadeh
Farid Lavizadeh
12,006 Points

Unless a named function is tied to an event, it will just run without the event occurring. Since getJSON(astrosUrl) is not tied to any event, it will run before a user clicks anything. To tie the named function to an event, a preceding anonymous function is used.