Cy Scott
Cy Scott

Reputation: 66

JavaScript Compile Error

I noticed a strange thing when writing some JS code. This compile error seems to happen across multiple browsers (tested: Chrome, IE, Safari). I am in no hurry for a solution but I could not figure out why this code won't compile:

    function fooBar1()//Compiles
    {
        return {
            x: 0,
            y: 1
        };
    }
    function fooBar2()//Compiles
    {
        return {x: 0, y: 1};
    }
    function fooBar3()//Compiles
    {
        return
        {
            x: 0
        };
    }
    function fooBar4()//Does not compile
    {
        return
        {
            x: 0,
            y: 1//Uncaught SyntaxError: Unexpected token : 
        };
    }

Upvotes: 4

Views: 3025

Answers (2)

Spudley
Spudley

Reputation: 168755

This is due to Javascript's Automatic Semicolon Insertion "feature".

I put the word "feature" in quotes because it's really anything but -- it's frankly a bit of a disaster; one of the worst design decisions I know of in a language.

Basically, the JS language is designed to have all statements ending with a semi-colon, but the original language design made allowances for coders who forgot it, and so if it sees a line break without a semi-colon, it tries to guess whether there should have been one there.

Unfortunately, there are some cases where this results in ambiguity and errors, and return statements are probably the worst for this.

In your last example, the { for the object being returned is on the line after the return statement. This is a classic case for this kind of bug. JS automatically inserts a semi-colon after return, and the the object that you intended to return is ignored.

Simple answer: just don't do it like this. Always put the object on the same line as the return statement. Memorise the fact that return needs the return data to be on the same line (or at least to start on the same line) as the return statement itself.

The closest you can get to your broken example and still have it work is shown by your first example.

return {
    x: 0,
    y: 1
};

As a final thought, you might want to consider running you JS code through a tool like jsLint, which will pick up errors like this (and other potential issues).

Upvotes: 1

lot
lot

Reputation: 1491

bugs like these can really drive one crazy, can't they?

my guess is that javascript parser adds a semicolon right after return in fooBar4. (it "thinks" you wanted it there)

at least when I modify any of your working functions by adding semicolon after return, same syntax error will appear

Upvotes: 0

Related Questions