The object literal syntax you are using is just part of JavaScript's syntax. You can use numeric or string literal as a property name as well as any valid variable name as a property name. Note that invalid variable names must be wrapped in quotes, but can still be property names (numeric literals being an exception).
That is, you can have obj = {'"': value}
, i.e. a quote, as a valid object property name. However, if you left off the apostrophes there it would be a syntax error.
The variable name syntax, e.g. {nameWithoutQuotes: "value"}
is allowed, as far as I can tell, for convenience. It has no special meaning and is treated as if it were a string literal property name. It would look very odd to have "
everywhere in an object literal definition, and it also makes sense when using similar accessor syntax. For example:
obj = {"with quotes": "q", withoutQuotes: "x"};
obj["with quotes"];
obj.withoutQuotes;
Note that the method of access with a property name that requires quotes also requires quotes whereas when quotes are not required access can be done without them.
As for why "obj" = "string"
is not allowed, other than the fact that it is invalid syntax, that is because the "obj"
literal does not create a reference in memory that can be assigned to. The obj = {}
notation creates a reference that is stored in obj
and memory is allocated for each of its properties as described by the literal syntax. You could make a similar statement about obj = "string";
It may also be worth nothing that the quotes cannot be omitted from a JSON string for property names. Many parsers will not allow it.