John Doe
John Doe

Reputation: 215

Uncaught Syntax error: unexpected token ( even though function is valid

I am trying to make a web application. I have a task controller in a separate .js file which I include in the main .html file:

<head>
  <script src = "tasks-controller.js"></script>
</head>

and the file tasks-controller.js:

tasksController = function() {
    var taskPage;
    var initialized = false;

    return
    {
        init: function(page) {
            if(!initialized)
            {
                 .... some manipulation with jQuery...    
                initialized = true;             
            }
        }
    }
} ();

Back in my main .html file I call tasks controller right after body closing element:

<script>
$(document).ready(function()
{
  tasksController.init($('#taskPage'));
}
</script>

When I test the file, in Google chrome tools, I get Uncaught SyntaxError: Unexpected token ( on line 8 of tasks-controller.js which is this line:

init: function(page)

along with another error that 'tasksController' is not defined when I call it above. Any suggestions to what I am doing wrong? Thanks!

Upvotes: 0

Views: 353

Answers (2)

Tushar
Tushar

Reputation: 87233

The ready method is where the error is. You missed the ) of ready.

See the highlighted code and comments in the code below.

$(document).ready(function() {
    tasksController.init($('#taskPage'));
}); // The ) you've missed
// ^^^

Other problem in your code is the return statement. If you put the object to the next line of return it will always return undefined. Automatic semicolon insertion will cause the code to put semicolon after return.

So, it'll be like return;.

Use following code:

tasksController = function() {
    var taskPage;
    var initialized = false;

    return {
        init: function(page) {
            if (!initialized) {
                ....some manipulation with jQuery...
                initialized = true;
            }
        }
    };
}();

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

Due to implicit semicolons, your code equals this:

return;
{
    init: function(page) {
        if(!initialized)
        {
             .... some manipulation with jQuery...    
            initialized = true;             
        }
    }
}

The return is returning nothing, and so the {} makes a new block. Now you can see why you have a syntax error.

Just change the first line to return { (no newline) and you should be good.

See Strangest language feature.

Upvotes: 0

Related Questions