0

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

2 Answers2

2

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    
};
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101
1

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

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120