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

Josephine Hedman
Josephine Hedman
6,399 Points

Can someone explain why the functions end up with the value 65 in the last example?

Hi, in the example of CPS (continuation-passing style), they give an example of functions that takes callbacks as arguments. Could someone be so kind and explain to my how the functions end up with the value 65 in the end? I've tried to go through the sequences but I'm not really getting it.

Thanks in advance!

function add(x, y, callback) {
// The x will be 5 and y will be 10 so sum will be 15 
// The sum value will be forwarded to callback and in callback we're calling subtract
  callback(x + y)
}
function subtract(x, y, callback) {
// The x will be 15 and y will be 2 so subtraction will be 13 
// The subtracted value will be forwarded to callback and in callback we're calling mutiply
  callback(x - y);
}
function multiply(x, y, callback) {
// The x will be 13 and y will be 5 so product will be 65
// The product value will be forwarded to callback and the n will be 65
  callback(x * y);
}
function calculate(x, callback) {
 // The x will be 5 
 //Value of 5 will be forwarded to callback & in callback we're calling add with 5
  callback(x);
}

calculate(5, (n) => {
  add(n, 10, (n) => {
    subtract(n, 2, (n) => {
      multiply(n, 5, (n) => {
        console.log(n); // 65
      });
    });
  });
});

Hope it helps. Let me know if you have still any doubts.

Thanks

1 Answer

Josephine Hedman
Josephine Hedman
6,399 Points

Thanks a lot! I get it now. Had some trouble understanding the order in which to read the callback function so it helped a lot by seeing it step by step :D

cheers :)