Why is same return type but result is difference [duplicate]

允我心安 提交于 2019-11-27 07:00:21

问题


I have two function of same return type in java script but return type is difference. The using code of snipped id below

function foo1()
    {
      return {
          bar: "hello"
      };
    }

    function foo2()
    {
      return
      {
          bar: "hello"
      };
    }

calling the function..

console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());

Output the result ....

foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined 

回答1:


That's because JavaScript interprets

return
{
    bar: "hello"
};

as return statement followed by block creation (which is ignored in runtime). Not as "return an object". And I really don't know why JavaScript devs made such decision.

Anyway ASI inserts ; after return resulting in the equivalent code:

return;
{
    bar: "hello"
};

The newline after return is the culprit. Don't use it if you wish to return something.




回答2:


Its automatic insert of the semicolon here. The rest of code is never reached.

function foo2()
{
  return    // get a automatic semicolon insert here
  {
      bar: "hello"
  };
}

Please have a look: Warning: unreachable code after return statement




回答3:


A javascript free you do without semicolon but it puts a automatic semicolon, that is why you get undefined Refer this

function foo1()
    {
      return {
          bar: "hello"
      };
    }

    function foo2()
    {
      return{
          bar: "hello"
      };
    }
    console.log("foo1 returns:");
    console.log(foo1());
    console.log("foo2 returns:");
    console.log(foo2()); 


来源:https://stackoverflow.com/questions/37045768/why-is-same-return-type-but-result-is-difference

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