0

I am following the following tutorial on how to make a space invaders game - http://www.html5rocks.com/en/tutorials/canvas/notearsgame/

However error message in the title is displayed when this code is executed and the game doesn't display. The invalid label indicates that the "y" at the start of the second line within the return function is the culprit of the error.

player.midpoint = function()
{
    return
    {
        x: this.x + this.width/2,
        y: this.y + this.height/2
    };
};

However when I take this code out the game runs fine, only when I press space to fire the game freezes as it requires the above function to fire bullets.

algorhythm
  • 3,304
  • 6
  • 36
  • 56
  • possible duplicate of [Automatic semicolon insertion & return statements](http://stackoverflow.com/questions/12745743/automatic-semicolon-insertion-return-statements) – Bergi Apr 25 '14 at 14:10

1 Answers1

4

Automatic Semicolon Insertion hit you. Your code is parsed as

player.midpoint = function() {
    return;
    {
        x: this.x + this.width/2,
        y: this.y + this.height/2
    }
};

where the braces form a block and x and y are labels of statements - and the trailing comma before y: is a syntax error.

You will need to put the returned expression in the same line as the return:

player.midpoint = function() {
    return {
        x: this.x + this.width/2,
        y: this.y + this.height/2
    };
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ah right so how do I fix it? I've tried writing the code as you have indicated above but it's still showing the y has having an invalid label – algorhythm Apr 25 '14 at 14:10
  • Ah sorry I didn't see the whole post as it was edited, working fine now! Didn't even realise that having semi-colons on a different line can throw an error. Is that only for JavaScript or throughout all languages? – algorhythm Apr 25 '14 at 14:15
  • 1
    No, semicolon rules are different for all languages. JavaScript is one of the more complicated ones since they are optional, yet sometimes omitting it can change the meaning of the program (you're lucky it threw an error - guess what would've happened if you tried to return an object with a single property only: the syntactically valid function would just return `undefined` completely out of the blue). – Bergi Apr 25 '14 at 14:22