copenndthagen
copenndthagen

Reputation: 50742

JavaScript SyntaxError: invalid property id

I am trying to execute the following JS code;

var foo = {
  func1:function(){
    function test()
    {
      alert("123");
    }();
    alert("456");
  },
  myVar : 'local'
};

But I am getting an error SyntaxError: invalid property id

What is wrong with the above code?

Upvotes: 5

Views: 26736

Answers (3)

Raja G
Raja G

Reputation: 6633

In my case it's very different, adding the answer here for others who might come across the same error.

I have an object like below

var obj = {
  case: ''
};

so when referring to the case attribute as obj. case, as case is a reserved word, my editor codeMirror raised an error.

After I renamed it from case to caseNumber it worked well. Similarly cant use if, else or switch and other JS keywords even as attributes as well.

Upvotes: 0

karaxuna
karaxuna

Reputation: 26940

wrap with ():

(function test(){
  alert("123");
}());

Or:

(function test(){
  alert("123");
})();

Upvotes: 3

James Allardice
James Allardice

Reputation: 165971

You have a syntax error:

var foo = {
    func1:function() {
        function test() {
            alert("123");
        }();
//       ^ You can't invoke a function declaration
        alert("456");
    },
    myVar : 'local'
};

Assuming you wanted an immediately-invoked function, you'll have to make that function parse as an expression instead:

var foo = {
    func1:function() {
        (function test() {
//      ^ Wrapping parens cause this to be parsed as a function expression
            alert("123");
        }());
        alert("456");
    },
    myVar : 'local'
};

Upvotes: 11

Related Questions