Why does the JS console return an extra undefined?

2019-01-29 14:38发布

问题:

This question already has an answer here:

  • Why does this JavaScript code print “undefined” on the console? 1 answer

Can someone tell me what's going on here (tested in Firefox and Chrome).

I have a simple function returning a closure.

function say (name) {
  var msg = 'hallo';
  return function () {
    console.log(msg, name);
  }
}

var sayName = say('joe');
sayName();

If check the browser console I get the expected result:

Hallo Joe

However, if I leave out the last line and run sayName() from the console I get the following:

Hallo Joe
undefined

Where is the extra undefined coming from?

回答1:

The console outputs the return value of the function you're executing.

See what happens if you put a return statement in your function e.g.

return function () {
    console.log(msg, name);
    return "If you run me from console you'll see this line";
}