I had an interview where the person asked me this question. Can anyone explains all the aspects so that i have a clear idea which structure to use when.
-
use the structure appropriate to the data – Jaromanda X Aug 30 '16 at 10:11
-
To be simple: Do you need named keys? Object! Don't? Array! The rest is opinion based. – eisbehr Aug 30 '16 at 10:11
-
Here is a good read for you: http://www.metaltoad.com/blog/javascript-understanding-objects-vs-arrays-and-when-use-them – Dat Nguyen Aug 30 '16 at 10:13
-
Beside this, an `array` is an `object` too in JS. – eisbehr Aug 30 '16 at 10:14
-
@JaromandaX thanks...actually he asked that both of them can do the same job at the end..Is there a striking difference i can put up which separates them totally. – Aman Seth Aug 30 '16 at 10:20
-
Possible duplicate of: http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript – eisbehr Aug 30 '16 at 10:21
1 Answers
Arrays:
- Arrays provide order, Object's don't (at least not yet).
- Arrays can be optimized (speed and even the memory footprint), when used as non sparse lists with items of the same type.
- Arrays provide a bunch of functions to work with this data-structure
Objects:
- Objects are more generic
- Using the Object as a Dictionary: lookups are faster than iterating over an Array to find the right item.
return itemsById[id]
- Code for Objects with the same hidden class can also be optimized.
Conclusion:
Arrays: use them if you think of the data as a list; same type improves performance but ain't a requirement.
To be more precise: lists have no gaps (missing indices), the data may have gaps, but the list shouldn't. If the list would have gaps, then the index has a meaning beyond just order, and it's probably a Dictionary with numeric keys.
Dictionaries: Plain Object used as a dictionary for the advantage of the fast lookup. Mentioned separate, because it's a different state of mind, having/dealing with a dictionary of items and dealing with an Object composing some properties.
Objects: A composition of properties of "some object". Like the body parts of a person. Or the "row" in a table of data: {id, firstName, lastName, ...}
Avoid enumerated properties. If you have sth. like {foo1, foo2, foo3, ...}
foo
is most likely a list of whatever, and should be built as such (just makes your life easier).
unless this object is a dictionary

- 11,958
- 1
- 14
- 23