Why does console.log say undefined, and then the correct value? [duplicate]
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?
Solution 1:
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:
The undefined
is the return value of console.log()
. This is standard behavior of Chrome's JS Console
Solution 3:
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:
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:
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.