Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some object-literal properties quoted and others not? [duplicate]

I see this all the time: object literals declared such that some keys are surrounded with quotes and others are not. An example from jQuery 1.4.2:

jQuery.props = {     "for": "htmlFor",     "class": "className",     readonly: "readOnly",     maxlength: "maxLength",     cellspacing: "cellSpacing",     rowspan: "rowSpan",     colspan: "colSpan",     tabindex: "tabIndex",     usemap: "useMap",     frameborder: "frameBorder" }; 

What is the significance of wrapping the first two property keys (for and class) with quotes, while leaving the others quote-less? Are there any differences at all?

I've been poking around the ECMAScript 5 specification; all I've been able to find is [Note 6 of Section 15.12.3, emphasis mine]:

NOTE 6 An object is rendered as an opening left brace followed by zero or more properties, separated with commas, closed with a right brace. A property is a quoted String representing the key or property name, a colon, and then the stringified property value. An array is rendered as an opening left bracket followed by zero or more values, separated with commas, closed with a right bracket.

However, this refers only to the stringification of JSON.

like image 241
ntownsend Avatar asked Feb 27 '10 20:02

ntownsend


People also ask

Do object keys need quotes?

Unless an object key is a numeric literal or a valid identifier name, you need to quote it to avoid a syntax error from being thrown. In other words, quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

What is meant by object literal?

Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.

What is the correct syntax for declaring an object literal?

Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.

How can we initialize an object in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).


1 Answers

Those are Javascript reserved words, and (though not really necessary) the syntax of the language requires that they be quoted.

Strictly speaking, pure "JSON" notation requires that all of the "key" strings be quoted. Javascript itself however is OK with keys that are valid identifiers (but not reserved words) being unquoted.

like image 86
Pointy Avatar answered Sep 21 '22 21:09

Pointy