Dev Bhatnagar
Dev Bhatnagar

Reputation: 15

Uncaught SyntaxError: Unexpected token : in chrome

Hi I am just beginning with Angular, coming across one error,while just writing a simple skeleton program

let mod1 = function()
{
  let task1 = function()
  {
    console.log('task one executed');
  };

  let task2 = function()
  {
    console.log('tasl 2 executed')
  };
  return 
  {
    t1: task1,
    t2: task2    //error here
  };
};

let newmod = new mod1();
newmod.t1();
newmod.t2();

I am coming across an error of:

'Uncaught SyntaxError: Unexpected token :' in the //commented in front of line

Upvotes: 0

Views: 888

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Cause

{ }

is not an object as one might think, but rather a block statement, commonly known in cases like:

 if(true) { } // a block statement
 while(true) { } // a block statement

So javascript expects it to contain statement, not key value pairs.

return
{
  alert("works");
}

But why does the compiler does not interpret it as an object? Well, thats because its not part of an expression, just remove the newline, so that it becomes part of the returned expression:

return { /* object */ }

TLDR: never ever start an expression in a newline

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68645

Automatically a ; is set after the return. After it JS Compiler thinks that you have a scope

{
    t1: task1,
    t2: task2   
};

And in this scope : throws an error. So it is just an scope not an object with properties initializations.

Replace

return 
{
    t1: task1,
    t2: task2    //error here
};

with

return {
    t1: task1,
    t2: task2    
};

Upvotes: 2

Related Questions