Why does this callback return undefined?

2019-07-11 21:10发布

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.

2条回答
手持菜刀,她持情操
2楼-- · 2019-07-11 21:54

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);
};
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-11 21:54

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);
查看更多
登录 后发表回答