Why does console.log say undefined, and then the correct value?

Michael Durrant picture Michael Durrant · Jun 21, 2014 · Viewed 77k times · Source
console.log("hi") gives 
undefined
hi

console.log(1+1) gives 
undefined
2

Whether it's a string or integer calculation, I get undefined then the correct answer.

Why do I get the undefined message? Is there a good way to avoid it?

Answer

James Allardice picture James Allardice · Jun 21, 2014

The console will print the result of evaluating an expression. The result of evaluating console.log() is undefined since console.log does not explicitly return something. It has the side effect of printing to the console.

You can observe the same behaviour with many expressions:

> var x = 1;
undefined;

A variable declaration does not produce a value so again undefined is printed to the console.

As a counter-example, expressions containing mathematical operators do produce a value which is printed to the console instead of undefined:

> 2 + 2;
4