Reputation: 2542
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?
Upvotes: 1
Views: 1204
Reputation: 944007
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.
Upvotes: 4