Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object declarations: Do strings as keys make a difference?

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?

like image 466
aRestless Avatar asked Dec 26 '22 04:12

aRestless


2 Answers

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" */
like image 141
James Donnelly Avatar answered Dec 27 '22 19:12

James Donnelly


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

like image 28
Naeem Shaikh Avatar answered Dec 27 '22 18:12

Naeem Shaikh