Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Callbacks Review

Routine Poutine
Routine Poutine
26,038 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,678 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.