10

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

rahularyansharma
  • 11,156
  • 18
  • 79
  • 135
  • javascript function must return anything so it returns undefined , when i use console.log("Hello World");return; it doesnot print undefined – rahularyansharma May 26 '12 at 07:33
  • 1
    The Node shell outputs the return value of whatever you input, in this case, undefined. – Michelle Tilley May 26 '12 at 08:19
  • Does this answer your question? [node.js displays "undefined" on the console](https://stackoverflow.com/questions/8457389/node-js-displays-undefined-on-the-console) – Ivar Dec 31 '20 at 16:32

1 Answers1

17

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.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • When I type `for (c in {}) { };` in the node console I still get `undefined`. I'm pretty sure that `for` is NOT a function. So I'm suspecting that your answer is incorrect or at least incomplete. – Andrew Savinykh Jun 03 '14 at 22:51
  • 1
    Sorry for this late response, totally missed the comment. Anyway it applies to all expressions. Every JavaScript expression (not only functions) returns something even though not every result can be assigned to a variable. – freakish Jun 06 '15 at 08:49
  • Is there a reference for this that every expression whatsoever returns something? – TMOTTM Mar 14 '18 at 22:42