console.log(myFunction()) returns undefined

回眸只為那壹抹淺笑 提交于 2019-11-30 21:10:52

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/48362507/console-logmyfunction-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!