0

What is the difference between an object create with this syntax: { prop1: val1, prop2: val2 }, and an object created with this syntax: { 'prop1': val1, 'prop2': val2 }?

And also, does the following code work?

var val1 = 10, val2 = 15;
var tmp1 = { prop1: val1 };
var tmp2 = { 'prop2': val2 };
alert(tmp1['prop1']); // I expect 10
alert(tmp2['prop2']); // I expect 15

P.S.: Sorry, I couldn't come up with a better title for my question. That reflects my lack of knowledge of JavaScript.

isekaijin
  • 19,076
  • 18
  • 85
  • 153

2 Answers2

4

There is no difference in your examples. You would need the quotes if any of your property names had spaces or special characters or were otherwise not a valid identifier:

{ prop1 with spaces: val1, 6prop2$-^: val2 } // illegal 
{ 'prop1 with spaces': val1, '6prop2$-^': val2 } // correct
Community
  • 1
  • 1
Wayne
  • 59,728
  • 15
  • 131
  • 126
3

No difference at all, although the string version lets you use characters that are not valid characters for identifiers.

You can do this with strings:

{ 'prop-1': val1, 'prop-2': val2 }

But not as identifiers:

{ prop-1: val1, prop-2: val2 }

And yes, that code works.

user113716
  • 318,772
  • 63
  • 451
  • 440