What Is an Array-Like Object in JavaScript?

Find out what an array-like object is in JavaScript

In JavaScript, an object is said to be "array-like" if it satisfies the following conditions:

  1. Has sequential/indexed access to elements/properties;
  2. Has a (non-negative) length property which tells how many elements the object has.

Furthermore, it can easily be converted into an array and you can iterate over its elements.

For example, creating an array-like object can be as simple as doing something like the following:

const obj = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

Some common examples of array-like objects in JavaScript include; NodeList, HTMLCollection, the arguments object in a function, etc.

Please note that an array-like object does not have access to array methods such as push, forEach, indexOf, etc. This is because it doesn't inherit array properties/methods from Array.prototype as the object is not constructed using Array or []. However, some array-like objects may choose to implement similar methods (like how the NodeList object implements the NodeList.prototype.forEach() method).

By default, an array-like object might not be usable with syntaxes that expect iterables (such as a for...of loop, the spread syntax, yield*, and destructuring assignment), unless it implements the iterable protocol.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.