12

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;
  }
};
Jindřich Mynarz
  • 1,563
  • 1
  • 16
  • 31

2 Answers2

11

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
  • 337,827
  • 72
  • 505
  • 443
  • 1
    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. – Jindřich Mynarz Jul 07 '10 at 12:56
  • 2
    @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 Jul 07 '10 at 13:03
5

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.

gblazex
  • 49,155
  • 12
  • 98
  • 91