aRestless
aRestless

Reputation: 1885

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?

Upvotes: 6

Views: 518

Answers (2)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

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

Upvotes: 6

James Donnelly
James Donnelly

Reputation: 128791

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" */

Upvotes: 6

Related Questions