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 trialNick Coffey
1,657 Pointsreturn vs callback? [Javascript]
Whats the difference between return and call back? Both gets back the same result in the example below. Since I saw callback in the javascript asynchronous course material, should I use callback when asynchronous functions are used?
function add(a, b, callback) {
callback(a + b);
}
add(2, 4, function(sum) {
console.log(sum); // 6
});
Return example:
function add(a, b, return) {
return(a + b);
}
add(2, 4, function(sum) {
console.log(sum); // 6
});
3 Answers
Nick Coffey
1,657 PointsAlright, one can store it in memory for later execution?
Jess W
9,490 PointsThis might help clear things up a little: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
This article is good too: https://dmitripavlutin.com/javascript-callback/#:~:text=The%20synchronous%20callback%20is%20executed,()%20and%20greet()%20functions.
I was only thinking of async callbacks when I answered your question, oops!
Nick Coffey
1,657 PointsThe asynchronous callback is executed after the execution of the higher-order function. -source: dmitripavlutin
I think that might be right. by higher order function, I think he means parent functions. Which would make sense.
Jess W
9,490 PointsRight, he means the higher order function is the function that has the callback as an argument. I hope this was helpful. I sure learned some things :)
Nick Coffey
1,657 PointsI realised that there is allot more: https://teamtreehouse.com/library/callback-functions-in-javascript
The callback function does not seem to be apart of of the JS fullstack track for some reason. Or maybe I'm bad at finding it.
Jess W
9,490 PointsWow, there is a lot to callbacks if it has its own course! You're right, I don't think it's in the Full Stack track. I think you can get a lot done with just a basic understanding of callbacks, but I'll have to take this course too when I get a chance.
Jess W
9,490 PointsJess W
9,490 PointsA callback is a function that you want to run some time later, like when a specific event happens. For example, if you wanted to run a function
foo()
when a button is pressed, you passfoo
as a callback like this:addEventListener("click", foo);
That sets things up so thatfoo
will automatically be called when your button is clicked.Use
return
when you want a function to immediately return a result.Does that help?