JavaScript Whitespace Syntax Error

2019-03-27 09:41发布

问题:

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?

回答1:

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.