2

I'm currently reading a book called "JavaScript and jQuery Interactive Front End Web Developement" by Jon Duckett. In the chapter on DOM, it mentions that

NodeLists look like arrays and are numbered like arrays, but they are not actually arrays. they are a type of object called a collection.

My question is, what is the difference between an array and collection in JavaScript and when should I choose one over the other?

1
  • They don't have a definite and official name like a collection. Sometimes they appear as a node list or an exotic array. Normally you don't chose to use them they are given to you as a result of a query. They are array like objects having index like properties (0,1,2,3,...) and a length property as well. They are mostly iterable too but they don't have direct access to the Array.prototype.
    – Redu
    Commented Sep 15, 2016 at 8:53

2 Answers 2

2

From https://developer.mozilla.org/it/docs/Web/API/NodeList:

Why is NodeList not an Array?

NodeList are used very much like arrays and it's tempting to invoke Array.prototype methods on them, however NodeList objects don't have any of the familiar Array methods.

JavaScript has an inheritance mechanism based on prototypes for both built–in objects (like Arrays) and host objects (like NodeLists). Array instances inherit array methods (such as forEach or map) because their prototype chain looks like the following:

myArray --> Array.prototype --> Object.prototype --> null (The prototype chain of an object can be obtained by calling Object.getPrototypeOf several times.)

forEach, map and the likes are own properties of the Array.prototype object.

Unlike arrays, NodeList prototype chain looks like the following:

myNodeList --> NodeList.prototype --> Object.prototype --> null

NodeList.prototype contains the item method, but none of the Array.prototype methods, so they cannot be used on NodeLists.

1

NodeLists are very similar to Array collections of elements, often referred to as “array-like”, but with a subtle difference - you’re missing out on a lot of JavaScript functionality by keeping your collection as a NodeList, such as true Array iteration and Prototypal methods.


The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.


NodeList to array

var myArray = Array.prototype.slice.call(myList, 0); undefined myArray.constructor.toString(); "function Array() { [native code] }"

Not the answer you're looking for? Browse other questions tagged or ask your own question.