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

Javascriptconsole.log

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

The undefined is the return value of console.log(). This is standard behavior of Chrome's JS Console

Solution 3 - Javascript

The console shows the return value of your input. console.log() doesn't return anything, so undefined.

You could just type directly into the console to get the result.

Solution 4 - Javascript

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.log reaches the console and is printed as well.

If a browser does not show the undefined, it means it has noticed that your console input only prints to the console, and so skips showing the result.

Solution 5 - Javascript

It returns the value of console.log(...).

Define two functions like this and you'll see why.

function functionA() {
  return 1; 
}
function functionB() {
  return;
}

The functionB() returns undefined.

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael DurrantView Question on Stackoverflow
Solution 1 - JavascriptJames AllardiceView Answer on Stackoverflow
Solution 2 - JavascriptadjanView Answer on Stackoverflow
Solution 3 - Javascriptcooper667View Answer on Stackoverflow
Solution 4 - JavascriptPurkkaKoodariView Answer on Stackoverflow
Solution 5 - JavascriptAli GajaniView Answer on Stackoverflow