Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify() and JavaScript Objects

I'm thinking maybe I missed something in JavaScript that I'm just picking up now.

I tried this code in Chrome console:

a = [];
a.name = "test";
JSON.stringify(a); 
// which returns value []
a = new Object();
a.name = "test";
JSON.stringify(a); 
// which returns value {"name":"test"}

What is the difference? I thought new Object() was a Microsoft JScript thing? What am I missing? Must have missed something in a spec somewhere. Thanks.

like image 959
BuddyJoe Avatar asked May 16 '11 17:05

BuddyJoe


2 Answers

a = new Object()

and

a = []

are not equivalent. But,

a = {}

and

a = new Object()

are.

like image 75
Anurag Avatar answered Nov 15 '22 03:11

Anurag


new Object() is equivalent to {} (except when it's not because of weird redefinition issues - but ignore that for now.) [] is equivalent to new Array(), to which you're then adding a .name property. JSON stringifies arrays in a special way that doesn't capture arbitrary property assignment to the array itself.

like image 28
Dan Davies Brackett Avatar answered Nov 15 '22 03:11

Dan Davies Brackett