[SOLVED] There is any difference between callback function and calling a function inside another function?

Issue

Let’s take this example:

function foo(callback){
        callback();
        baz();
  }

  function baz() {
        console.log('Hello from baz');  
   }

   foo(baz);

It looks like they are doing the same task. Or callback and calling a function inside another function are the same thing?

Solution

Except you aren’t using the callback the way callbacks are supposed to be used. Callbacks are supposed to get the interim results from a previous function. Here’s an example

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

function subtract (a, b) {
  return a - b;
}

This is the callback

function doLater (val) {
  if (val > 0) {
    console.log("positive");
  } else if (val ==) {
    console.log("zero");
  } else console.log ("negative");
}

function doOp (a, b, mathOp, callback) {
  var res = mathOp(a,b);
  callback(res);
}

doOp (2,3, add, doLater);

vs.

doOp (2,3,subtract, doLater);

Answered By – ControlAltDel

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.