6

I have the following JavaScript code:

var counter = 0;
function printCounter(){
   console.log("counter=" + ++counter);
   setTimeout(printCounter, 1000);
}
printCounter();

I expect that it should print this output:

counter=1
counter=2
counter=3
...

But instead it prints following:

counter=1
undefined  // <-- Notice this "undefined"
counter=2
counter=3
...

Why does it print "undefined" after the first iteration?

Important: I see such behavior only when the code executed in the JavaScript console. If it's the part of a page, it works fine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anton Moiseev
  • 2,834
  • 4
  • 24
  • 30
  • The real canonical question is probably *[Chrome/Firefox console.log always appends a line saying 'undefined'](https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined)* – Peter Mortensen Oct 20 '20 at 17:22

1 Answers1

9

It's because the "printCounter()" function itself returns undefined. That's the console telling you the result of the expression.

Change "printCounter()" by adding return "Hello Anton!"; to the end :-)

It's a little confusing to say it "returns undefined"; really, it has no explicit return, but it's the same effect.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    ...and so the `undefined` is the result of *the REPL evaluation* but since the *asynchronous* timer is running it will continue to call `console.log`... –  Apr 21 '12 at 21:36
  • Yes, thank you, you are right. I was confused because it's not the case for all browsers. – Anton Moiseev Apr 21 '12 at 21:40