0

I wrote some code in the Node.js console, and noticed sometimes it return an undefined.
See the following code.

Some lines return undefined but some don't.
What does the undefined mean?

PS D:\test\hello> node
> "two\nlines"
'two\nlines'
> var s = "hello, world"     
undefined
> s.charAt(0)
'h'
> s.charAt(s.length -1)
'd'
> var anyString = 'Mozilla';
undefined
> console.log(anyString.substring(3, 0));
Moz
undefined
MarshallOfSound
  • 2,629
  • 1
  • 20
  • 26
Aaron
  • 2,383
  • 3
  • 22
  • 53
  • 5
    `undefined`, in this context, means the statement doesn't have anything to return. More details at [node-js-displays-undefined-on-the-console](http://stackoverflow.com/questions/8457389/node-js-displays-undefined-on-the-console) – asgs May 08 '15 at 10:05
  • But what does the last line , it returns `undefined` but also returns `Moz`? – Aaron May 08 '15 at 10:09
  • There are two statements there. the inner one returns Moz whereas the outer doesn't return anything. Hence `undefined`. – asgs May 08 '15 at 10:11

1 Answers1

3

But what does the last line , it returns undefined but also returns Moz?

> console.log(anyString.substring(3, 0));
Moz
undefined

console.log explicitly outputs to the console, which is the Moz you're seeing. It then returns a value (or well, it doesn't), which is the value undefined, which is logged to the console because you're in the interactive environment and that's what it does.

The point of using the interactive command line is to be able to try operations and see their result instantly, without complex alert or debugging setups. You type a command, you see its result. Sometimes that result is the value undefined, sometimes it's another value.

deceze
  • 510,633
  • 85
  • 743
  • 889