Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  124] [ 5]  / answers: 1 / hits: 16265  / 12 Years ago, sat, april 21, 2012, 12:00:00

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.


More From » undefined

 Answers
8

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.


[#86080] Friday, April 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;