Search code examples
javascriptarraystype-conversionnodelisthtmlcollection

Why does JavaScript not convert array-like objects to arrays?


While learning about DOM manipulation I noticed that Document methods such as getElementByTagName or querySelectorAll return HTMLCollection or NodeList objects which, however much they look like arrays, have to be converted to arrays using Arrays.from() if we want these collections to have the very useful array methods. I am wondering why this is so. Is there any particular reason why JS does not automatically convert these collections to arrays?

Edit: It has been brought to my attention that NodeList has forEach() in all major browsers.


Solution

  • The DOM collections have their own types, instead of being Array (or at least array subclass) instances, because they are very different from arrays. They are mere views on the DOM, they are not containers storing the elements themselves. They are immutable (i.e. you cannot .push() on them) or even live views (i.e. they always represent the selection in the current state of the document). Also they can only hold DOM nodes, you cannot put arbitrary values inside them like you can insert into arrays.

    Sure, they are array-like in that they have indexed properties and a .length, but that's where the similarity ends. Notice that it is only JavaScript that allows you to access the contents with index properties, according to the pure language-agnostic DOM you would use the .item(index) method. All this is why DOM collections got their own hierarchy and have nothing to do with the Array type that is built into JavaScript.