An array-like object in JavaScript is an object that has numeric indices and a length property but does not necessarily inherit from the Array
prototype.
While these objects resemble arrays in terms of their structure (indexed elements with a length
property), they lack many of the built-in methods and functionalities provided by true arrays such as forEach
, map
, filter
, and others.
To work with array-like objects, you can either use a for loop to iterate over their elements, or convert them to real arrays using methods like Array.from()
or the spread operator.
let arrayLikeObject = {
0: 'apple',
1: 'banana',
2: 'orange',
length: 3
};
let realArray = Array.from(arrayLikeObject);
console.log(realArray); // ['apple', 'banana', 'orange']
Common examples of array-like objects in JavaScript include the arguments
object inside functions, the NodeList
returned by DOM queries, and the result of certain API calls.