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 Callbacks Review

Routine Poutine
Routine Poutine
26,050 Points

Is "callback" a keyword? Not as a parameter, but as part of the function's body?

Hi, I thought callbacks were simply functions passed as arguments, but this lesson's format is more advanced than that. At least I find it harder to grasp. When writing "callback" in the parameters, that makes sense to me as a place for an argument. However, what about in the function's body. My apologies if this is not clear.

Best,

Matt

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

callback is not a keyword, and you're on the right track here. In this example, callback is the name of a parameter where a function will be passed in. Then, in the body of the function, we call the function that was passed in to the callback parameter. We can call it whatever we want.

function add(a, b, fancyFunc) {
    fancyFunc(a + b);
}

add(2, 4, function(sum) {
    console.log(sum); // 6
});

I renamed it fancyFunc and it still works. In this case, we're passing an anonymous function as the argument for fancyFunc. But we could also have passed in a function that has a name.

function add(a, b, fancyFunc) {
    fancyFunc(a + b);
}

function myLogger(val) {
    console.log(val);
}

add(2, 4, myLogger);

I'm declaring a function named myLogger. Then, I'm passing that function in as the 3rd argument to the add function. So myLogger is now in the fancyFunc parameter. In the body of add, it's going to call whatever function is passed in. So by calling fancyFunc it ends up calling myLogger.

Let me know if you have more questions.