Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird javascript syntax error

In Firefox I received a weird syntax error, as this is not trivial, and an interesting syntax error I'd like to post here because I don't know it's happening.

Should file this as a bug report?

I was testing some scripts from here: here

It gave me a syntax error. SyntaxError: invalid label at line 5.

app.directive("alertable", function()
{
    return 
    {
        restrict : "A",
        link: function(scope, element, attrs) 
        {
            element.bind("click", function() 
            {
                alert(attrs.message);
            });
        }
    };
});

And this one, don't:

app.directive("alertable", function()
{
    return { // fix???
        restrict : "A",
        link: function(scope, element, attrs) 
        {
            element.bind("click", function() 
            {
                alert(attrs.message);
            });
        }
    };
});
like image 767
Ismael Avatar asked Jul 07 '13 12:07

Ismael


1 Answers

This behavior is by design.

Semicolons in Javascript are optional. (ASI)
The parser inserts an implicit semicolon after the return line, and assumes that the { begins a code block. (like after an if or for)

The first line in that code block is not actually valid code, so you get that error.

This happens because return is a valid statement both with and without an operand.

Similarly, the code

return
4;

Is parsed as return; 4;.

like image 70
SLaks Avatar answered Oct 04 '22 01:10

SLaks