-1

I don't undetstand why the following function doesn't return {bar:"hello"} and instead it returns undefined.

function foo2() {
    return
    {
        bar: "hello"
    };
}
Ming Li
  • 11
  • 1
  • 3
    There's a carriage return after `return` and before the opening brace. Try `return {` instead. – sherb Dec 05 '14 at 05:30
  • 2
    You might want to read up on [automatic semicolon insertion](http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) in JavaScript. – Ben Dec 05 '14 at 05:31

2 Answers2

5

That's because its compiled to the below because of javascript's auto semi-colon insertion.

function foo2() {
    return; // notice the semi-colon here?
    {
        bar: "hello"
    };
} 

And since return; is called, the function terminates without going to the next line of code. To make it work correctly just put the opening bracket right after return as in return {

You'd be better off by using semi-colons than omitting them. Want reasons? check out Dangers of Javascript's automatic semicolon insertion

Amit Joki
  • 53,955
  • 7
  • 67
  • 89
  • Note that this is the *exact* example for the dangers of ASI that is shown in pretty much every JS tutorial, styleguide, book, etc. ever created in the history of JS. Anybody who has spent even 3 seconds learning JS knows this. – Jörg W Mittag Dec 05 '14 at 05:32
  • Well, _maybe_ four seconds... :-) – sherb Dec 06 '14 at 00:08
1

A semicolon is inserted after return by JS engine.

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

Change to this is ok

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

About auto semicolon insertion, aka ASI, you may want to read this, this and this.

Leo
  • 11,955
  • 4
  • 37
  • 58