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

人盡茶涼 提交于 2019-11-26 02:39:12

问题


I have 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 it prints \"undefined\" after first iteration? Important: I see such behavior only when the code executed in JavaScript console. If it\'s the part of a page, it works fine.


回答1:


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 :-)

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



来源:https://stackoverflow.com/questions/10263190/why-does-this-javascript-code-print-undefined-on-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!