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?

1
  • 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. Commented Jul 10, 2013 at 15:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

how would you access the property that is not a valid identifier?
facedesk. I should have known that. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.