Welcome to the Treehouse Community
Looking to learn something new?
Ryan Smith3,757 Points
Difference between collections and arrays (is there one?)
This may be a very stupid question, but having just started working through some of the document.getElementById lessons and working with 'collections', I'm wondering what's the difference between collections and arrays? Are there any? Is collection just another name for arrays? They seem to be the same thing and work the same way. I tried looking through more info on collections on the MDN and was reading about 'NodeList' but was having trouble following it.
Jennifer NordellTreehouse Teacher
Hi there, Ryan Smith ! I received your request for assistance. They are very array-like structures. But instead of an array that contains things like integers or strings, they contain nodes from the DOM. I don't know if you've gotten to object-oriented programming yet, but this might make more sense when you do. The things being stored in these
HTMLCollections have styles associated with them, properties, attributes, you name it and it goes way beyond just a simple string or integer.
Now, having said that, as far as accessing them using subscripting like
let allDivs = document.getElementsByTagName("div"); they work very much like an array. To get the second div recorded in the
allDivs variable you could do
let secondDiv = allDivs. But unlike true arrays they are missing functions like
.pop() etc. They do, however contain the
.length property just like a true array.
But luckily, they are easily converted to a true array should you need the other methods like
Check out the Array.from method.
Long story short: they are much like a watered-down version of an Array that stores objects from the DOM.
Hope this helps!
edited for additional information
In this answer, I am talking specifically about
HTMLcollections but please note that there are other data structures that are generically termed as "collections" including (but not limited to), arrays, objects, sets etc.