console.log(myFunction()) returns undefined
I'm new to JavaScript, and I try to play around with it to understand all in-and-outs. I write
function greet() {
console.log("Hi");
};
console.log(greet());
And the result of it in the console is
> Hi app.js:2
> undefined app.js:4
I assume this is because greet()
inside console.log
first calls the function, which prints out "Hi"
. We get first line of log. But where did the second line come from?
Then I thought because Hi
is overall result of greet()
, then console.log
basically calls variable Hi
, but in this case the result would be is not defined
, not undefined
In JavaScript, if nothing is returned from the function with the keyword return
then undefined
is returned by default.
var data = greet();
console.log(data);// undefined, since your function does not return.
Is equivalent to:
console.log(greet());
The second output is the returned result from the function. Since you are not returning anything from the function hence prints undefined
.
To print 'Hi' in the second console you have to return that from the function.
function greet() {
console.log("Hi");
return 'Hi';
};
console.log(greet());