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 Introduction to jQuery Events Callback Functions

Why use the callback function in this case?

In the "Callback Function" video in JQuery, the anonymous function logs something to the console. For the sake of simplicity, why not use the console.log() directly in the 'click' function instead of making a function out of console.log() ? I'm sure that I'm overlooking something, as a student, but it just seems to me that the callback function doesn't add much here.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

I'm guessing you're refering to this code at about 0:30 in the video:

$('button').click(function() {
    console.log('Done!');
});

Since click() sets up something to handle an event that will happen at an indeterminate time in the future it requires a function that it will call when that event occurs. That is essentially what a callback function is.

You can pass the console.log function directly to click of course, so whenever the button in clicked it will call console.log() as it's callback:

$('button').click(console.log);

The trouble is, what are we passing to console.log? When we pass console.log directly we aren't able to pass along arguments. We won't be passing along the simple string "Done!" Instead it will be passed what every event handler is passed, the event object, and it will log that to the console instead.

I see what you mean. Thanks!