5

I'm looking at the Google Maps API tutorial, and I see this:

<script type="text/javascript" 
        src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps', version:3, other_params:'sensor=false'}]}"></script>

Why is modules wrapped in single quotes?

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
stone
  • 841
  • 3
  • 16
  • 26

4 Answers4

8

It's a good practice to wrap keys in quotes, even though not strictly required, in order to avoid the possibility of conflicts with JavaScript reserved words.

Imagine if you had class instead of modules - class happens to be a reserved word in JavaScript, even though it is not actually used in the current specification.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • 3
    @stone if you are happy with Daniel's response you should accept it by clicking the green tick on the left. – kazanaki May 07 '10 at 14:14
  • @MathiasBynens: I didn't intend to say that reserved works are invalid identifier names. Only that it is often considered good practice to wrap key in quotes (especially for backward compatibility with ES3). – Daniel Vassallo Mar 05 '12 at 21:48
  • @DanielVassallo Fair enough. Just be aware that in ES5 this is no longer the case. (Also, reserved words in ES3 are different from those in ES5.) – Mathias Bynens Mar 05 '12 at 22:11
1

In fact, in most JSON implementations (because it's actually a JSON string), like jQuery's getJSON, it's obligatory to put all strings, whether they represent values or properties, within double-quotes.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • 4
    The "double quotes" is the correct way to go for JSON, since they are mandatory in the JSON spec. – Boldewyn May 08 '10 at 06:52
1

The currently accepted answer is incorrect — reserved words are valid identifier names, so they’re allowed as unquoted property names in JavaScript.

From Unquoted property names / object keys in JavaScript, my write-up on the subject:

Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

[…]

Bracket notation can safely be used for all property names.

[…]

Dot notation can only be used when the property name is a valid identifier name.

I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.

Screenshot

Community
  • 1
  • 1
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
0

It's not required unless:

  1. The property is named the same as a keyword/reserved
  2. The property has special chars
  3. The object is intended to be used as JSON
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210