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

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

For some reason, I'm still having trouble understanding this first example. Could anyone break it down?

I think I have a pretty good handle on callback functions, but for some reason, this first example still mystifies me. I understand what it's doing, but how? I don't know. When the function add is called, function(sum) is passed as the callback argument? What does that mean?

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

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

Thanks so much in advance!

1 Answer

Steven Parker
Steven Parker
210,487 Points

"function(sum)" defines an anonymous function that takes a single argument into a parameter named "sum".

Since they are passed as arguments themselves, it's common for callbacks to be anonymous (have no name).

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Thank Steven, I was just looking at the syntax incorrectly and couldn't see that it was an anonymous function being declared. Just one of the many benefits of staring at the code too long :)