Home > Software design >  simple function isn't calling the callback
simple function isn't calling the callback

Time:04-01

const five = function() {
  console.log(5)
}

const func = function(callback) {
  console.log(3)
  callback
  console.log(7)
}

func(five)

I would like to know why I have in the output

3
7

instead of

3
5
7

I tried to put callback() with parentheses and I got an error, why?

CodePudding user response:

Even though the function is assigned to a variable you need to call it as a function, with parentheses.

const five = function() {
  console.log(5)
}

const func = function(callback) {
  console.log(3)
  callback()
  console.log(7)
}

func(five)

CodePudding user response:

The issue with your code is that you aren't calling callback with parentheses.

To invoke a function in JavaScript, you need to use parentheses at the end, even if you don't need to pass in any parameters.

So, change your callback line from this:

callback;

To this:

callback();
  • Related