user784637
user784637

Reputation: 16162

Is declaring an associative array as a new Array() the same as declaring an associative array as an object {}?

Is the object whiteStripes the same exact thing in both cases?

var whiteStripes = {'Jack' : 'White', 'Meg' : 'White'};

var whiteStripes = new Array();
whiteStripes['Jack'] = 'White';
whiteStripes['Meg'] = 'White';

Upvotes: 1

Views: 122

Answers (2)

Guffa
Guffa

Reputation: 700840

No, it's not the exact same thing.

Both will work, because an array is also an object, but if you want just an object you should not create an array to get one.

These would result in the exact same thing being created:

var whiteStripes = {'Jack' : 'White', 'Meg' : 'White'};

var whiteStripes = new Object();
whiteStripes['Jack'] = 'White';
whiteStripes['Meg'] = 'White';

Upvotes: 3

Andy Meyers
Andy Meyers

Reputation: 1581

While you will still be able to access the properties the same way (whiteStripes['Jack']) in both instances when you declare whiteStripes = new Array(); you are saying it has all the properties and attributes of an array like length for example. If you are not intending to use it as a true array (pop, push, length, etc.) then don't use a JavaScript array.

Upvotes: 4

Related Questions