Answers ( 2 )

  1. 2017-01-06 10:01

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

    Working ?

    If it is function, please tell it that it is a function.

  2. 2017-01-06 10:01

    The reason are optional semicolon in JS.

    JS treats your code like this:

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

    Many semicolon in JS are optional. Sometimes this is an advantage (see code golfing for example). But on other occasions like yours this results in unexpected errors.

    In foo1() you have an opening { after the return, so the parser will first try to look for the respective closing }. In foo2(), however, the parser has no reason to guess, that there should be more to parse, so it just inserts the (optional) semicolon and runs the code as is. The object in the next row is perfectly (syntactically) valid code - no reason to implicitly change anything about it.

◀ Go back