Why oh why? 😂
Ever wondered, why undefined is logged whenever you're messing around within a Browser's Dev Tools or any other JS run time environment?
Then this is for you!!
node
Welcome to Node.js v22.22.2.
Type ".help" for more information.
> let x = 45;
undefined
> let y = 78
undefined
> x==456 || y==78
true
> console.log(x)
45
undefined
>
TLDR
The output received after evaluation.
The phenomena
The host environment prints the result of every expression.
expression : (x === 456 || y === 78)
prints the result true but no undefined was printed!
However, the statements like below do not return a value.
let x = 45; OR console.log(x)
the above statement did not return any value, causing "undefined" to be printed in the logs.
The cause
- Because the host environment is in it's interactive mode.
First, understand that console.log() is not the main purpose here, it is a "side effect".
The main purpose is evaluation of the latest expression. Imagine the REPL environment effectively acting like this behind the scenes:
// 1. it takes your code string (input),
// 2. evaluates it (via eval()), and
// 3. returns the result
function executeInREPL(input) {
return eval(input);
}
So if you do console.log(x), it would print the value of "x" but since the evaluation did not "return" any value, "undefined" will be logged additionally.
So, the final cause is the result of evaluation.
Top comments (0)