Why console gives "undefined" after printing a output?

Why console gives "undefined" after printing a output?

Given in the above image what you expect the console to print out?

42, Right. But did you notice? That it also gives "undefined" in its second line of output. Why is that? let's dive deep into it and understand what actually works behind it.

The above code snippet gives "undefined" in its second line of output is due to Repls.

What is Repl?

Repl is a acronym which stands for read, evaluate, print, loop. It creates a sandbox( coding enviroment) for us to simplify our coding experience. It can have built-in function or testing functions or inbuild debugger. It is quite common in scripting languages.

How Repls work?

So as the name suggest, it will first read all the code that you have written in the terminal. Then, it will evaluate all the expressions and operations including arithmetic, loops, strings, arrays or objects. After the evaluations, it will print the result. The most common way of printing results into the console that people use is "console.log". The final step is loop, which means the control will go back to get more inputs to read.

So, in these example,

let a = 42;
{
    let a = 100;
}
console.log(a)

output -> 42
          undefined

The repl evaluates the assignment and we are not returning anything. Then it goes on simply printing the value of 'a' as 42 after the evaluation and as a default return type, it returns 'undefined' which gets printed in the second line of the output.

Conclusion -

These is how repls work in each segment when we are executing a code in the browser console.