In JavaScript, an object is said to be "array-like" if it satisfies the following conditions:
- Has indexed elements (i.e. object has sequential access to its properties);
- Has a (non-negative)
length
property which tells how many elements the object has.
An array-like object can easily be converted to 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 };
An array-like object can also potentially / possibly have gaps like the following:
const obj = { 0: 'foo', 5: 'bar', 7: 'baz', length: 8 };
They can also have random key ordering, for example:
const obj = { 5: 'bar', 7: 'baz', 0: 'foo', length: 8 };
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.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.