Yarin
Yarin

Reputation: 183779

Understanding Javascript object initialization keys

Is there any difference between the following?:

var object1= {
  a: 0,
  b: 1,
  c: 2
};

vs

var object2= {
  'a': 0,
  'b': 1,
  'c': 2
};

Upvotes: 7

Views: 4948

Answers (4)

rsp
rsp

Reputation: 111424

The answer by jessegavin already explains everything that you asked about, but let me add one thing that you didn't asked about but might need to know in the future.

All of these are valid JavaScript object literals:

{  a:  0,  b:  1,  c:  2 }
{ 'a': 0, 'b': 1, 'c': 2 }
{ "a": 0, "b": 1, "c": 2 }

but only the last one is valid JSON. Not properly quoting the keys in JSON is probably the main reason of programs producing invalid JSON, and invalid JSON seems to be the main source of problems that people have with AJAX.

Not exactly the answer to your question but still it is relevant and may save you some trouble in the future.

Upvotes: 6

jessegavin
jessegavin

Reputation: 75660

There's no difference in your example. There would be a difference if you wanted your property names to be a number or have spaces (both of which are valid, but strange).

var object3 = {
  '123': 0,
  'hello world' : 1
}

// This is valid
alert(object3['123']); // -> 0
alert(object3['hello world']); // -> 1

// This is not
alert(object3.123); // -> Syntax Error

If you have two minutes you might find this page VERY helpful.
http://bonsaiden.github.com/JavaScript-Garden/#object.general

Upvotes: 13

Mike Lewis
Mike Lewis

Reputation: 64167

Both of those are equal because in javascript, object attrs. can either be strings or plain text.

Upvotes: 0

bensiu
bensiu

Reputation: 25594

No difference. Both syntax are correct

Upvotes: 0

Related Questions