Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...