Why does the JS console return an extra undefined?

2019-01-29 14:17发布

This question already has an answer here:

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条回答
Ridiculous、
2楼-- · 2019-01-29 14:50

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