1

I have the following code:

 var factory = {
        query: function (selectedSubject) {
           ..
        }
 }

In Javascript is this the same as:

 var factory = {
        'query': function (selectedSubject) {
           ..
        }
 }

I have seen both used and I am not sure if there is any difference.

3 Answers3

3

The standard requires a property name to be one of:

PropertyName :
   IdentifierName
   StringLiteral
   NumericLiteral

that is, all of these are valid:

 obj = {
       "query": ....
       'query': ....
        query:  ....
        12e45:  ....
   }

Note that, contrary to the popular opinion, the standard does not require a name to be a valid identifier, only an "identifier name". This effectively means that you can use JS reserved words as property names:

x = {
    if: 100,
    function: 200,
}
console.log(x.if + x.function) // 300

Not that it's terribly useful in everyday programming, just a funny fact worth knowing about.

georg
  • 211,518
  • 52
  • 313
  • 390
2

You can use both, but if there are spaces you can't use the first option. That's why there is a second option.

Bart Langelaan
  • 529
  • 4
  • 10
  • 2
    There's another reason. If the property name is a reserved keyword, such as `delete`, `if`, or `class`, it also must be quoted. – Alexey Lebedev Apr 21 '13 at 11:07
  • 1
    @AlexeyLebedev: nope. `foo={if:100}` is valid javascript. – georg Apr 21 '13 at 11:18
  • @thg435: maybe the spec says so, but in reality it depends on the JS parser. In IE `foo={if:100}` is invalid. Even in Chrome and FF `;{if:1};` is invalid, while `;{iif:1};` is valid. – Alexey Lebedev Apr 21 '13 at 11:32
  • 1
    @AlexeyLebedev: IE might be broken, but Chrome follows the standard 100%. `;{if:1};` is not an object literal, hence the error. – georg Apr 21 '13 at 11:34
  • thg435: you're right, I haven't thought that in this context `iif` is a label in a block and not a property name. Like in this example: `function foo() { x: alert(1) }` – Alexey Lebedev Apr 21 '13 at 11:44
-1

Valid JSON requires "" to surround property name of an anonymous object, but you can omit them if the property name is not reserved word or does't contain some special chars. Generally it is more safe to use "".

Grzegorz Kaczan
  • 21,186
  • 3
  • 19
  • 17
  • 2
    No, in JSON you can't omit double quotes or use single quotes instead. In JavaScript you can. – Alexey Lebedev Apr 21 '13 at 11:03
  • 4
    JSON has nothing to do with native JS objects, they don't follow the same rules – zerkms Apr 21 '13 at 11:03
  • JSON was derived from JS. It has ALOT to do with it. It is simplified version of JS native objects tho. Thats why i said that JSON requires "", JS does not. See http://tools.ietf.org/html/rfc4627 – Grzegorz Kaczan Apr 26 '13 at 05:57