views:

208

answers:

1

Why does this cause a syntax error for the return statement:

var FOO = (function($)
{
    return
    {      
        init: function()
        {

        }
    }
})(jQuery);

Whereas this doesn't:

var FOO = (function($)
{
    return {      
        init: function()
        {

        }
    }
})(jQuery);

Why is there a difference?

+19  A: 

It's not about the whitespace, it's about automatic semicolon insertion by JavaScript.

ECMAScript specification says

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

This means that your code

var FOO = (function($)
{
    return
    {      
        init: function()
        {

        }
    }
})(jQuery);

gets translated as

var FOO = (function($)
{
    return; // <- JavaScript will insert a semicolon here.

    {      
        init: function()
        {

        }
    }
})(jQuery);

So FOO will be undefined after the function is executed.

For your other code, JS won't insert any semicolon and it will work correctly JS will insert semicolon after your literal object and it should work fine. [EDIT: Correction as pointed out by kagnax]

This means that you should always terminate your statements with semicolon. Letting JS engine insert semicolon can introduce very subtle bugs, which would take hours to debug. You can use a tool like JSLint which will warn you of missing semicolons.

SolutionYogi
Actually, for his "other code" JS **will** insert semicolon, but only after object literal — as explained in the section of specs you quoted — *ReturnStatement*s are candidates for ASI :)
kangax
kangax, I didn't notice that his other literal was also missing a semicolon. I will update the answer.
SolutionYogi
Some convinience, huh? I did not realize that Javascript will mess around with my code making such subtle but profound modifications. I do not want this 'convinience'. +1 for the taken to bascics explanation
mfeingold
Another reason to include the opening brace on the same line as the keyword =)
Jani Hartikainen