node.js displays "undefined" on the console
Recently I installed node.js on my Windows 7 machine.
On execution of JavaScript, I get an undefined message along with successful execution of the expression.
What's wrong here? I have not noticed any other side effects.
Solution 1:
The JavaScript functions always return something. If you don't specify something to return in the function, 'undefined' is returned by default (you can check this out in Firebug too).
Don't worry though, this doesn't affect anything, you can ignore it.
Solution 2:
Just write "hello world";
and hit enter... it will return "hello world"
instead of undefined
, thus no undefined
is displayed. console.log
returns undefined
and also logs arguments to console so you get multiple messages.
Solution 3:
As pointed out by others, javascript function will always return undefined if you do not specify any return value. You can just ignore it. It's not going to cause any harm. But if it's annoying you too much then you can turn it off in repl. Repl has this property ignoreUndefined which is set to false by default. You can set it to true. Try this:
module.exports.repl.ignoreUndefined = true;
Solution 4:
Well, the question was made some years ago, but there is still another way to explain what is happening here.
Try next command:
console.log("Hello World") || "Bye World";
As mentioned function console.log()
returns undefined
normally and you can choose a better return value. Since Non-strict (abstract) comparison considers undefined
equal to false
the ||
operator allows you that choice.
Considering that it is just a debugging tool, this is unnecessary in general use, but helps to understand that console displays text sent to stdout and also evals the command and displays the returned value, or undefined if no value was received.