console.log(myFunction()) returns undefined

后端 未结 1 1375
难免孤独
难免孤独 2020-12-10 23:45

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(g         


        
相关标签:
1条回答
  • 2020-12-10 23:53

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

    0 讨论(0)
提交回复
热议问题