Monde
Monde

Reputation: 25

Trying to understand Callback function

I'm creating a simple callback function trying to understand how it works.

function cbFunction(x, y, z) {
  return x + y + z
}

function caller(x, y, z, cbFunction) {
  console.log('In caller function!')
  // your code here
  if (typeof cbFunction === "function") {
    cbFunction (x, y, z)
  }
}

caller(1, 2, 3, cbFunction)

I'm invoking the cbFunction inside the caller function. Could you help me to understand why it isn't adding x, y, z? I'm learning JS as a beginner and thank you for your help!

Upvotes: 0

Views: 68

Answers (1)

Spectric
Spectric

Reputation: 32002

It is adding the numbers - you just aren't doing anything with the result returned by cbFunction.

Instead, return the result returned by cbFunction:

function cbFunction(x, y, z) {
  return x + y + z
}

function caller(x, y, z, cbFunction) {
  console.log('In caller function!')
  // your code here
  if (typeof cbFunction === "function") {
    return cbFunction(x, y, z); //<-- return
  }
}

console.log(caller(1, 2, 3, cbFunction))

Upvotes: 1

Related Questions