Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this JavaScript code print "undefined" on the console?

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.

like image 603
Anton Moiseev Avatar asked Apr 21 '12 21:04

Anton Moiseev


People also ask

Why does console print undefined?

This is because console. log() does not return a value (i.e. returns undefined). The result of whatever you entered to the console is first printed to the console, then a bit later the message from console.

What does undefined in console mean?

Undefined: It means the value does not exist in the compiler. It is the global object. Type: Null: Object.

How do I print a JavaScript console?

log() You should use the console. log() method to print to console JavaScript. The JavaScript console log function is mainly used for code debugging as it makes the JavaScript print the output to the console.


1 Answers

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.

like image 81
Pointy Avatar answered Sep 30 '22 17:09

Pointy