Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why undefined in node.js hello world example after console.log

Tags:

node.js

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

enter image description here

like image 456
rahularyansharma Avatar asked May 26 '12 07:05

rahularyansharma


People also ask

Why do I get undefined after console log?

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.

What does undefined mean in node JS?

undefined , in this context, means the statement doesn't have anything to return.


1 Answers

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.

like image 192
freakish Avatar answered Sep 18 '22 08:09

freakish