views:

61

answers:

2

Is there a difference between quoted and un-quoted JavaScript object property/method names?

For example, what is the difference between these two:

var obj1 = {
  property1 : "Value 1",
  method1 : function() {
    return true;
  }
};

var obj2 = {
  "property1" : "Value 1",
  "method1" : function() {
    return true;
  }
};
+4  A: 

There is no difference in JavaScript. However you will have to quote property names that happen to be reserved words (such as class), or names that contain invalid characters (such as first-name).

Daniel Vassallo
So, I think, this is really just a question of coding style. But with the limitations imposed on JavaScript by the necessary quoting of reserved words, it should be more consistent to quote properties/methods all the time.
jindrichm
@jindrichm: Yes, you could be consistent in quoting all the property names, but on the other hand you could also be consistent in using property names that are valid variable names. In general I tend to not quote, but I'm not particularly committed to either style... Note that if you use property names that are not valid variable names, you will not be able to use the dot notation to access the properties: `myObject.myProperty`, but you will be limited to using the subscript notation: `myObject['myProperty']`.
Daniel Vassallo
+2  A: 

Up until ES 3 you need to quote reserved words of the language (new, default, class, etc.). In the new version, however, this will be unnecessary.

But since ES 5 is not well-supported yet, you need to stick with quoting all reserved words.

If you don't want to memorize the full list of words, you better off with quoting everything.

Extra: this is why you don't have float and class properties on an element. You have to use cssFloat/styleFloat and className instead.

Another addition is that you need to quote every key in a JSON string. The reason is because they wanted it to be language independent, in order not to interfere with stupid restrictions like the one in ES3.

galambalazs
I think you refer to *ES3*, because *ES3.1* was simply [renamed](http://en.wikipedia.org/wiki/ECMAScript#ECMAScript.2C_5th_Edition) to *ES5*, when ES4 was abandoned.
CMS
yes i was just typing to fast, and forgot to check, thx for the typo... :)
galambalazs