JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Callbacks Review

Josephine Hedman
Josephine Hedman
6,272 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,272 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 :)