isekaijin
isekaijin

Reputation: 19742

How do JavaScript members/properties work?

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.

Upvotes: 0

Views: 181

Answers (2)

Wayne
Wayne

Reputation: 60414

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

Upvotes: 4

user113716
user113716

Reputation: 322492

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.

Upvotes: 3

Related Questions