Duncan
Duncan

Reputation: 1024

What is the difference between these two notations for Javascript objects/associative array?

What is the difference between this

var person = {
    name: "Bob",
    age: "99"
};

and this?

var person = {
    "name": "Bob",
    "age": "99"
};

Or do they mean the same thing? If they do, what if I want the key to be an object? How would I specify the object as the key if name means "name"?

Upvotes: 1

Views: 138

Answers (3)

1983
1983

Reputation: 5963

They mean the same thing. Valid keys are identifiers, string literals, or numeric literals. See http://ecma-international.org/ecma-262/5.1/#sec-11.1.5

You can't yet use objects themselves as keys, but WeakMap objects as proposed for EcmaScript 6 will solve this. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

There is no difference. Quotes are only necessary if you want to use a string as a property name, but that string is not a valid identifier. Further,

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation.

(source)

Object literal syntax is covered in-depth on MDN.

Upvotes: 3

Jon
Jon

Reputation: 437326

They are equivalent in this case, but the quoted version allows you to use keys that are not valid JS identifiers. For example, this does not work:

{ -test: 42 }

while this does:

{ "-test": 42 }

You cannot specify an object as the key no matter what.

Upvotes: 0

Related Questions