user799825
user799825

Reputation: 39

simple function isn't calling the callback

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?

Upvotes: 0

Views: 46

Answers (2)

Viradex
Viradex

Reputation: 3748

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

In summary, this is the fully working code.

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

const func = function(callback) {
  console.log(3);
  callback(); // This line has been modified
  console.log(7);
}

func(five); // Should output: 3, 5, 7

Upvotes: 2

isherwood
isherwood

Reputation: 61053

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)

Upvotes: 3

Related Questions