-7

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?

Andy
  • 61,948
  • 13
  • 68
  • 95
  • Because the console tries to helpfully log the result of your expression. If you run `3 + 4` in the console, it'll log `7`. No surprise there. – DCoder Aug 16 '13 at 09:56
  • @Ashwin, the last line of the code `sayName();`. @DCoder, I'd never noticed that before, that's why it came as a surprise. Thanks for your answer. – Andy Aug 16 '13 at 10:05
  • `sayname` doesn't have a return statement so it returns `undefined`. – Patrick Stephansen Aug 16 '13 at 10:10

1 Answers1

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";
}
Matias
  • 26
  • 2