7

Is there any difference between the following?:

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

vs

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

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah the Javascript Garden is fantastic! It explains things really well.
I won't link to JavaScript Garden, mainly because it does not feature a complete explanation of this - we didn't set out to cover everything on the topic, only the quirkest bits; I was going to suggest MDC but their page on Objects is severely outdated (JavaScript 1.0? Seriously?), so I guess this will do for now ;)
6

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.

Comments

0

No difference. Both syntax are correct

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.