2

This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

{
    'name': 'Teddy',
    'last': 'Monster'
}

But then I also see the more common, no quote params:

{
    name: 'Teddy',
    last: 'Monster'
}

Is there a reason one would use single quote params? Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

4 Answers4

3

You can't define this hash:

{
   function: 'foo'
}

But you can define

{
   'function': 'foo'
}

Personally, I use the former way, if there's no reserved keywords as keys (as to not clutter the code, like you've pointed out).

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
1

Technically the second form is invalid according to the JSON spec, but it works fine in all mainstream Javascript engines.

kprevas
  • 2,452
  • 1
  • 17
  • 14
1

A quick Google search finds this answer on this very website. Essentially there's no functional difference if you're talking about object literals, but the properties can't be reserved words like "class" or "namespace". Wrapping the property in quotation marks allows those words to be used

Community
  • 1
  • 1
James Long
  • 4,629
  • 1
  • 20
  • 30
0

Single quoting allow you to use any valid string, including reserved keywords or characters than would be invalid in an identifier

Example:

{
  'return' : 'ok',
  'with-hyphen' : '123'
}
Axel Fontaine
  • 34,542
  • 16
  • 106
  • 137