2
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.

tckmn
  • 57,719
  • 27
  • 114
  • 156
dsp_099
  • 5,801
  • 17
  • 72
  • 128

2 Answers2

8

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);
};
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • 1
    You've answered the question. Juts on a quick sidenote though, say that the secondFunction had a setTimeout(), and contained the return in it and delayed it somehow. It seems if that's the case, the original one doesn't wait on it and just returns undefined again. – dsp_099 May 25 '13 at 03:00
  • What would be the option if thats the case? – Soyas Jul 08 '22 at 03:47
2

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);
Elle
  • 3,695
  • 1
  • 17
  • 31