Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between quoted and un-quoted JavaScript object properties [duplicate]

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;
  }
};
like image 742
Jindřich Mynarz Avatar asked Jul 07 '10 12:07

Jindřich Mynarz


2 Answers

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

like image 198
Daniel Vassallo Avatar answered Oct 29 '22 03:10

Daniel Vassallo


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.

like image 35
25 revs, 4 users 83% Avatar answered Oct 29 '22 03:10

25 revs, 4 users 83%