Why does Chrome console.log always append a line saying 'undefined'?
Table of contents
Introduction
Have you noticed this behaviour when you type console.log()
in the Chrome console window?
You are getting two values here-
Hello
undefined
The first output is the expected one but what about the second output? Any guess?
It is because console.log
does not explicitly return something and therefore undefined is printed.
We can observe the same with many expressions:
A variable declaration(like above) does not produce or return a value so again
undefined
is printed on the console.
The function would return a value when invoked, however, in the image above, we have just defined it and it doesn't produce anything. Hence, undefined is printed.
There's a counter situation as well. In the image below, undefined isn't printed.
Can you guess why? Let's look at how this works behind the scenes
How does it work?
The Chrome console is REPL which is a command-line tool and that is the reason for the behaviours that I mentioned above.
It reads the JavaScript that I type into it, evaluates the code, prints out the result of the expression, and then loops back to the first step t be ready for more input.
Let's take an example-
console.log("Hello,REPL");
👉It reads the code first
👉It will evaluate the code which will always return something, however in the above example there is nothing to evaluate. It is a statement, hence, it returns undefined.
Otherwise if it was an arithmetic, loop structure, string, array or object manipulation or any other possible operation which returns something it would have not been undefined(snippet below)
function test(a,b){
return a+b;
}
test(2,3);
5
👉Now it prints whatever is left to print. REPL moves to print this console.log("Hello, REPL")
👉And, we reached the final step and it loops back to a state where the REPL can take our next set of instructions.
Closing Thoughts
I hope the explanation helped you in understanding the flow behind the scenes! REPL is a useful concept and it's important to know! Please let me know if I have missed anything!
References
You can read more on REPL and Chrome Console:-
https://codewith.mu/en/tutorials/1.1/repl
https://developer.chrome.com/docs/devtools/console/javascript/
https://blog.bitsrc.io/why-does-console-log-return-undefined-e06d44b4d0f8
Subscribe to my newsletter
Read articles from Rajashree Parhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rajashree Parhi
Rajashree Parhi
I write what I learn along my coding journey!