Understanding Javascript Object Initialization Keys

Is there any difference between the following ?:

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

against

 var object2= { 'a': 0, 'b': 1, 'c': 2 }; 
+7
source share
4 answers

There is no difference in your example. It 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 can find this page VERY useful.
http://bonsaiden.github.com/JavaScript-Garden/#object.general

+13
source

Jessegavin's answer already explains everything you asked for, but let me add one thing you didn't ask about, but maybe she will need to know in the future.

These are all valid JavaScript literals:

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

but only the last JSON is valid. Incorrect key quoting in JSON is probably the main reason for programs that produce invalid JSON, and invalid JSON seems to be the main source of the problems that people face with AJAX.

Not quite the answer to your question, but still it is relevant and may save you some problems in the future.

+6
source

No difference. Both syntaxes are correct.

0
source

Both are equal because in javascript, attrs objects. may be a string or plain text.

0
source

All Articles