admin管理员组

文章数量:1426016

There are some questions floating around here on stackoverflow about JSON being a subset of the Object Literal Notation. But I couldn't find an answer to a specific question of mine.

Is there any difference between

var obj = {keyName : "value"};

and

var obj = {"keyName" : "value"};

in JavaScript?

There are some questions floating around here on stackoverflow about JSON being a subset of the Object Literal Notation. But I couldn't find an answer to a specific question of mine.

Is there any difference between

var obj = {keyName : "value"};

and

var obj = {"keyName" : "value"};

in JavaScript?

Share Improve this question edited Dec 23, 2014 at 18:34 Naeem Shaikh 15.7k7 gold badges53 silver badges91 bronze badges asked Sep 24, 2014 at 12:58 aRestlessaRestless 1,8852 gold badges21 silver badges27 bronze badges 1
  • 1 It is not "strings as keys". Keys are always strings. It's a notational matter of whether or not you quote them. A better title would be "Does quoting keys make a difference?" – user663031 Commented Sep 25, 2014 at 15:34
Add a ment  | 

2 Answers 2

Reset to default 6

Yes. The difference is that the file size of the latter will be two bytes larger to account for the two extra " characters in your code.

Otherwise no, there's no difference between the two example objects you've given.

var obj = {keyName : "value"};

obj.keyName;       /* "value" */
obj["keyName"];    /* "value" */
var obj = {"keyName" : "value"};

obj.keyName;       /* "value" */
obj["keyName"];    /* "value" */

No difference, except that the 2nd one will add two extra " characters in your code which will cost you two extra bytes.

And the reason the two types of declaring object properties with or without quotes is because You can try,

var obj = {"key Name" : "value"};

and still access it as

obj['key Name']

But not

var obj = {key Name : "value"};

Thinking this way, there is a difference

本文标签: javascriptObject declarations Do strings as keys make a differenceStack Overflow