Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Javascript object initialization keys

Tags:

javascript

Is there any difference between the following?:

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

vs

var object2= {
  'a': 0,
  'b': 1,
  'c': 2
};
like image 312
Yarin Avatar asked Mar 15 '11 03:03

Yarin


1 Answers

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

like image 98
jessegavin Avatar answered Sep 30 '22 08:09

jessegavin