Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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)?

like image 768
Elias Zamaria Avatar asked Dec 11 '22 18:12

Elias Zamaria


2 Answers

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".

like image 118
Pointy Avatar answered Dec 14 '22 06:12

Pointy


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

foo.new = 'bar';

Instead, do this:

foo['new'] = 'bar';
like image 33
hunterloftis Avatar answered Dec 14 '22 08:12

hunterloftis