最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Why does this callback return undefined? - Stack Overflow

matteradmin4PV0评论
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.

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.

Share Improve this question edited May 25, 2013 at 2:53 tckmn 59.4k27 gold badges118 silver badges156 bronze badges asked May 25, 2013 at 2:47 dsp_099dsp_099 6,13120 gold badges78 silver badges132 bronze badges 1
  • 2 You forgot the chain the return value from callback. – Ja͢ck Commented May 25, 2013 at 2:50
Add a ment  | 

2 Answers 2

Reset to default 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);
};

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);
Post a comment

comment list (0)

  1. No comments so far