Elias Zamaria
Elias Zamaria

Reputation: 101083

"Expected identifier" error from IE8 and IE7 when object has "new" as property name

I have a web page that I am testing in IE8, and it is telling me that the page has errors. I tried to come up with a simple example and I came up with this:

<!DOCTYPE HTML>
<html>
<head>
  <script>
  var stuff = {
    "foo": {
      "new": 42
    }
  };
  var thing = stuff.foo.new;
  </script>
</head>
<body>
</body>
</html>

It can be tested here.

This is the error I see:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Timestamp: Mon, 21 Jan 2013 23:11:52 UTC


Message: Expected identifier
Line: 11
Char: 25
Code: 0
URI: file:///C:/Documents%20and%20Settings/Administrator/My%20Documents/ie8PropertyNameTest.html

IE7 shows a similar error. It works fine in every other browser I tested the page in, including newer versions of IE. Does anyone know what is causing this problem and how to avoid it (other than the obvious solution of picking some other name)?

Upvotes: 4

Views: 4408

Answers (2)

hunterloftis
hunterloftis

Reputation: 13799

If you use new as a key, don't do this:

foo.new = 'bar';

Instead, do this:

foo['new'] = 'bar';

Upvotes: 3

Pointy
Pointy

Reputation: 413737

new is a JavaScript reserved word. You can get to the property with:

var thing = stuff.foo["new"];

(I'll wager). You'll save yourself some trouble by calling the property something like "isNew".

Upvotes: 10

Related Questions