Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this callback return undefined?

function firstFunction(num, callback) {
  callback(num);
};

function secondFunction(num) {
  return num + 99;
};

console.log(firstFunction(56, secondFunction));
undefined

If I call console.log from within secondFunction, it returns the value.

Why not? What's the point of setting up callbacks if I can't get the value out of them to use later? I'm missing something.

like image 708
dsp_099 Avatar asked Jul 30 '26 22:07

dsp_099


2 Answers

In your function firstFunction, you do:

callback(num);

Which evaluates to

56 + 99;

Which is then

155;

But you never return the value! Without a return value, a function will simply evaluate to undefined.


Try doing this:

function firstFunction(num, callback) {
  return callback(num);
};
like image 51
tckmn Avatar answered Aug 01 '26 11:08

tckmn


firstFunction does not return anything, plain and simple! That is why when you console.log the return value, it is undefined.

The code in question:

callback(num);

calls callback and then does nothing with the returned value. You want:

return callback(num);
like image 36
Elle Avatar answered Aug 01 '26 10:08

Elle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!