Why console.log() in browser returns undefined

Have you ever wondered why the browser prints undefined after printing your message in the console? To understand this let us explore what the browser console is.

What is the browser console?

The console is a command line tool that is part of the browser. It is also called a REPL which is an acronym for Read, Evaluate, Print, Loop. REPL is a feature provided by scripting languages.

What is a REPL and what does it do?

REPL creates a sandbox/environment to explore our code. The job of REPL is to do the following:

  1. Read: Read the code written in the language native to the REPL (Example: JavaScript in case of Node.js REPLY, python in case of Python REPL)

  2. Evaluate: Evaluate and run the code. These are operations that can be anything like arithmetic operations, string/object manipulation and running loops.

  3. Print: Print to the console. Once all the operations are evaluated, print the result of the operation or if we provide any console.log() then print those.

  4. Loop: Return to the state when the computer is ready to read the next input.

Let's see an example. Suppose we run a simple operation 2+2, what do think the console will print?

The console will first read the JavaScript code 2+2, evaluate the operation to 4, print the result of the operation to the console and return to listen to the next input.

what happens when we run console.log("hello") in the browser?

Now with our understanding of what REPLs are and how they work, let's see what happens when we run console.log() in the browser console.

  1. the console.log("hello") statement is read by the REPL/browser console

  2. there is no operation performed so the result of the console.log() evaluation result is undefined

  3. the browser print the console.log("hello") message and the result (undefined) of the evaluation from step 2

  4. the computer returns to a state to read the next input operation.

Conclusion

we saw with our understanding of REPL why the browser's console prints undefined when we run console.log(). Thank you for reading!