1

I have a question regarding field names in js object literals. I have a function test that looks like this:

function test()
{
    var o1 = {f1:"Hello"};
    var o2 = {"f1":"Hello"};
    alert(o1.f1 + " " + o2.f1);
}

and the result is that a box appears with "Hello Hello" written in it (the test was inspired by seeing code that used strings for all of the field names). My question is, what is the difference between the two objects? Is there a difference between quoting the field name and not? Are there any specific style guidelines if the two are functionally the same?

James
  • 2,483
  • 2
  • 24
  • 31
  • 1
    One interesting thing to note: although the two are identical as far as javascript is concerned, when dealing with the JSON language (which is obviously very similar to the javascript notation), you are required to quote the names. So personally, I just quote the names all the time anyway, as a habit, since I often deal with JSON objects in other languages. – Joe Enos Jul 10 '13 at 15:22

1 Answers1

4

My question is, what is the difference between the two objects?

They are identical.

Is there a difference between quoting the field name and not?

Quoted property names can be things which are not valid identifiers.

e.g. { "foo-bar": 1 } is fine but { foo-bar: 1 } is a syntax error.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • how would you access the property that is not a valid identifier? – James Jul 10 '13 at 15:15
  • 2
    See [How do I reference a javascript object property with a hyphen in it?](http://stackoverflow.com/questions/7122609/how-do-i-reference-a-javascript-object-property-with-a-hyphen-in-it) – Quentin Jul 10 '13 at 15:16
  • facedesk. I should have known that. Thanks – James Jul 10 '13 at 15:17