i just started with node.js . So for starting with Hello World example node.js beginner book . when i type the command console.log("Hello world");
. Its prints Hello World on console . That what i expect from this code but in next line its also prints the undefined
i install the nodejs from this link for windows installation of nodejs for windows
here below is screenshot also for this
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.
undefined , in this context, means the statement doesn't have anything to return.
Every JavaScript function returns something. When you define function like this:
function test() {
var x = 1;
}
then test()
returns undefined
. The same applies to the console.log
function. What it does is that it passes the arguments to the display. And that's all. Thus it returns undefined
.
Now Node JS shell works in such a way that whenever you input a function, variable, etc. it displays the value it returned. Thus console.log('Hello world!');
passes Hello world!
to the screen and returns undefined
, which then Node JS shell displays.
That's more or less how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With