Search code examples
javascriptreturnsyntax-errorlinefeedcurly-brackets

Why JS throws syntax error, if there is a linefeed between return and {


I always thought, that new lines in JS sourcecode doesn't matter. Why new lines do matter sometimes?

Error:

function x(y)
{
    return 
    {   y : y,
        z : y*2
    } 
}
console.info(x(5).z);

Throws a SyntaxError: missing ; before statement at z : y*2 (pointing to the :)

But this is working:

function x(y)
{
    return (
    {   y : y,
        z : y*2
    } )
}
console.info(x(5).z);

shows 10

This is also working:

function x(y)
{
    return {
        y : y,
        z : y*2
    } 
}
console.info(x(5).z);

Solution

  • There are 2 problems: The ";" are automaticaly added by the browser on the return line, and you missed one ";" after the object declaration in the return. You should never rely on automatic addition of ";", because you wouldn't be abble to minify your javascript code after that.

    You wouldn't have this problem by using the "1TBS" notation. (a notation that i also call the "Egyptian Notation"): So always put the curly brace at the end of the previous statement. http://en.wikipedia.org/wiki/Indent_style

    The question has already be debatted here: Is there a way I can make jslint work with curly braces on the next line of my javascript?

    So the right notation for your code should be:

    function x(y){
        return {
            y : y,
            z : y*2
        }; 
    }
    console.info(x(5).z);
    

    You may use jshint to check your code style.