A collection is not an array

Share this article

I’m occassionally irked by the fact that a collection of DOM elements (more formally called a NodeList) can’t be manipulated like an array, because it isn’t one. However it does look like one, and thinking it is one is a mistake made so often by JavaScript novices that for our upcoming JavaScript Reference I felt it necessary to note this point for every single DOM object that is, or returns, a collection.

You can iterate through a collection like an array:

for(var i=0; i<collection.length; i++)
{
	//whatever
}

But you can’t use Array methods like push(), splice() or reverse() to manipulate it.

Except that you can, if you take the next step and convert it into an array. This is in fact trivial:

function collectionToArray(collection)
{
	var ary = [];
	for(var i=0, len = collection.length; i < len; i++)
	{
		ary.push(collection[i]);
	}
	return ary;
}

The code above is fully cross-browser, and is called with the original collection as an argument:

var elements = collectionToArray(document.getElementsByTagName('*'));

However if you only need to deal with browsers that support native object prototyping (Opera, Firefox and Safari 3) then you can simply create a toArray() method of NodeList:

NodeList.prototype.toArray = function()
{
	var ary = [];
	for(var i=0, len = this.length; i < len; i++)
	{
		ary.push(this[i]);
	}
	return ary;
};

Which can then be called as a method of the individual collection:

var elements = document.getElementsByTagName('*').toArray();

There is one obvious disadvantage to this conversion (however it’s done), which is that the resulting array will no longer be a NodeList. Obvious, yes, but relevant because it has two implications:

  • It will lose the properties and methods it inherited from NodeList. However NodeList only has one property (its length, which is also available for an array), and one method (the item() method, which is usually redundent anyway, since members can still be referred to with square-bracket notation). So this loss is not at all significant
  • It will no longer be a live collection. A NodeList is a reference to a collection of objects, and if that collection changes (for example, elements are added or removed) the NodeList will automatically update to reflect that change; conversely our array is a static snapshot of the collection at one point in time, and so won’t update in response to changes in the DOM. Depending on your application, that could be significant.

Frequently Asked Questions about JavaScript Collections and Arrays

What is the difference between a collection and an array in JavaScript?

In JavaScript, a collection is an object that contains a group of elements. These elements can be of any type, including other collections. Collections are often used when you need to work with a group of similar items, but they do not have the same methods and properties as arrays. On the other hand, an array is a special type of object that represents a list of items. Arrays have built-in methods for manipulating and querying their contents, such as push, pop, shift, unshift, and so on.

How can I convert a collection to an array in JavaScript?

There are several ways to convert a collection to an array in JavaScript. One of the most common methods is to use the Array.from() function. This function creates a new array instance from an iterable object. Here is an example:

let collection = document.getElementsByTagName('div');
let array = Array.from(collection);

In this example, the collection of div elements is converted into an array.

Can I use array methods on a collection?

No, you cannot directly use array methods on a collection because collections are not arrays. However, you can convert a collection to an array using Array.from() or the spread operator, and then use array methods on the resulting array.

What are the advantages of using collections over arrays in JavaScript?

Collections in JavaScript are often used when dealing with DOM elements. They provide a live link to the DOM, meaning that if the DOM changes, the collection is automatically updated. This is something that arrays cannot do. However, arrays have more built-in methods for manipulating data, so they are often more convenient for data manipulation tasks.

What is an Array-like object in JavaScript?

An array-like object is an object that has a length property and can store elements at specific indices, just like an array. However, it does not have array methods like push, pop, etc. A common example of an array-like object is the arguments object available within all functions.

How can I identify if an object is an array or a collection in JavaScript?

You can use the Array.isArray() method to check if an object is an array. This method returns true if the object is an array, and false otherwise. There is no built-in method to check if an object is a collection, but you can check if it has certain properties that are common to collections, such as length or item.

Can I use the spread operator to convert a collection to an array?

Yes, you can use the spread operator (…) to convert a collection to an array. The spread operator works by spreading the elements of the collection into a new array. Here is an example:

let collection = document.getElementsByTagName('div');
let array = [...collection];

What is the difference between a static and live collection in JavaScript?

A live collection in JavaScript is a collection that automatically updates when the DOM changes. This means that if elements are added or removed from the DOM, the collection is automatically updated to reflect these changes. A static collection, on the other hand, does not update when the DOM changes. Once it is created, it remains the same regardless of changes to the DOM.

Can I add or remove elements from a collection in JavaScript?

No, you cannot add or remove elements from a collection directly. Collections are read-only. However, you can modify the DOM elements that the collection is based on, which will in turn update the collection if it is a live collection.

Can I use forEach on a collection in JavaScript?

No, you cannot use forEach directly on a collection because collections are not arrays. However, you can convert a collection to an array using Array.from() or the spread operator, and then use forEach on the resulting array.

James EdwardsJames Edwards
View Author

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form