Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...