2

In all of the tutorials I have seen so far, items in dictionaries have been initialized like:

var myObj = { foo:"bar", fooBar:"fooBaz" };

why aren't the keys quoted? Are they not just strings?

What would I do If I wanted a space in my dictionary key?

Luke
  • 5,567
  • 4
  • 37
  • 66
  • if you use quote you have to use array notation to access the property i think. – AL-zami Jan 17 '15 at 15:55
  • it might be useful http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – AL-zami Jan 17 '15 at 16:07

1 Answers1

5

Quotes are optional when keys are proper identifiers or numbers. For other keys, quotes are required:

var foo = {
  identifier: "no quotes",
  "@balloonz are pretty": "quotes necessary"
};

Property names that are not identifiers must be accessed using the [ ] operator:

if (foo["@balloonz are pretty"] != null) {
  // ...
}

The semantics of property access via [ ] and . are the same; it's just a syntactic distinction.

if (foo.identifier != null) {
  // ...
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    what is the significance of @? Is it a special symbol in JS, or is is just special in the same way a space is special and adds to invalidating the string from being a "proper identifier" – Luke Jan 17 '15 at 15:53
  • A commentor just said that using a quote makes it so that you can't use the "." notation, is this true? – Luke Jan 17 '15 at 15:57
  • "for other keys,quotes are required" will you explain this statement in your answer?? – AL-zami Jan 17 '15 at 15:57
  • 1
    @LukeP It's a character that can't be part of an identifier, but otherwise it's not special. – Pointy Jan 17 '15 at 15:57
  • @al-Zami it means that for strings that are not valid identifiers, quotes are required. – Pointy Jan 17 '15 at 15:58
  • @LukeP you cannot use `.` notation to access properties whose names are not identifiers, yes. That's because the syntax requires names that are identifiers. You can use `[ ]` notation for non-identifier property names, and the semantics of `.` and `[ ]` are the same. – Pointy Jan 17 '15 at 15:59
  • oh duh. That's actually, somethign obvious, but can we move this to chat, so we can talk about cleaning this question up a bit – Luke Jan 17 '15 at 16:00
  • I want to delete most of these comments and have al delete his comment, and then you can just ad the bit about the "." notation as an addition to your answer – Luke Jan 17 '15 at 16:01
  • @LukeP I'll add that to the answer, but I don't see any problem with the comments. They might be useful to somebody someday. – Pointy Jan 17 '15 at 16:01