I just found out that Arrays inherit directly from Object in javascript. I'm finding the difference between an array and an object is fairly minuscule.
How do i know when to use one over the other?
I just found out that Arrays inherit directly from Object in javascript. I'm finding the difference between an array and an object is fairly minuscule.
How do i know when to use one over the other?
When you need to depend on the order of the elements in the collection, use Arrays, when order is not important, use objects. Order is not guaranteed in objects, but they provide for fast key-value pair lookups.
They are just different data structures, they serve different purposes.
Array
extendsObject
and provides properties likelength
and methods likepush()
andpop()
.Think of an object as a hash table and an array as a list.
E.g. you can use arrays as queue or as a stack which would not be possible with objects.
On the other side if you want to store data and want to access a specific datum directly, you would use an object.
In the end it boils down to the question which data structure is the right one for the job. Maybe neither of them is and you would need a tree instead (which can be implemented via objects).
Objects
are a good candidate if you have a unique key.Example
Array
vs.Object
:As you can see finding an object is much more expensive with an
array
(loop). Using anobject
you will not have access to all thearray
helper methods (sort/push/etc) but you can still iterate an objects' properties using afor...in
loop.I'd use an
Array []
when I'm dealing with a list of objects the same type* (like a list of strings) that I want the order of and anObject {}
when I'm dealing with something that I want properties of (and the properties are of different types, usually).For example:
* This is just my preference. Arrays can contain elements of multiple different types.
Objects keys are strings; array keys are integers. JavaScript objects are maps (
String -> anything
) and arrays are lists (ordered collections ofanything
).Does that help?
You often use arrays when you have a series of related items that you want ordered and indexed.