0

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!

2
  • 2
    Why do you think it doesn't add the numbers? You're not doing anything with the result other than returning it and caller doesn't care about the return value either. Commented Jul 10, 2021 at 21:21
  • 2
    It actually is adding x, y and z, however you're not doing anything with the result of cbFunction, you could try return cbFunction(x, y, z) in the caller functionthen console.log(caller(1, 2, 3, cbFunction)); Commented Jul 10, 2021 at 21:22

1 Answer 1

1

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))

Sign up to request clarification or add additional context in comments.

2 Comments

I see it now. Thank you so much for the explanation!
Yeah, i tried but it asked me wait for a couple mins. I will.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.