Single quotes in a JavaScript object object

I am studying 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 are modules enclosed in single quotes?

+4
javascript html
source share
4 answers

It’s good practice to wrap the keys in quotation marks, although this is not strictly required to avoid the possibility of conflicts with reserved JavaScript words ,

Imagine that class instead of modules - class is a reserved word in JavaScript, even if it is not used in the current specification.

+7
source share

In fact, in most JSON implementations (because it is actually a JSON string), such as jQuery getJSON , it is imperative to insert all strings representing values ​​or properties in double quotes.

+1
source share

The current accepted answer is incorrect - the reserved words are valid identifier names, so theyre allowed as unquoted property names in JavaScript.

From Unquoted property names / object keys in JavaScript , my related entry is:

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

[...]

The parenthesis designation can be safely used for all property names.

[...]

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

I also created a tool that tells you whether any property name can be used without quotes and / or with dot notation. Try it at mothereff.in/js-properties .

Screenshothot

+1
source share

This is not required if:

  • The property is called the same as the keyword / reserved
  • The property has special characters.
  • The object is intended to be used as JSON.
0
source share

All Articles