What is an array-like object?
An array-like object
is an object that looks like an array, but is not a real array.
It has:
- numeric indices (
0,1,2, ...), - a
lengthproperty, - but no array methods (
push,map,forEach, and so on).
Examples of array-like objects:
1. arguments inside a function
javascript
function showArgs() {
console.log(arguments);
}
showArgs(10, 20, 30);
// Arguments(3) [10, 20, 30, callee: ƒ, Symbol(Symbol.iterator): ƒ]arguments looks like an array, but:
javascript
console.log(arguments[0]); // 10
console.log(arguments.length); // 3
console.log(arguments.map); // undefined2. DOM collections
javascript
const divs = document.querySelectorAll("div");
console.log(divs);NodeList and HTMLCollection are also array-like objects.
They contain elements by index and have length,
but do not have methods like map, filter, and so on.
Why it is not an array
A real array inherits methods from Array.prototype,
but an array-like object does not.
javascript
Array.isArray(arguments); // falseHow to turn an array-like object into a real array
1. Via Array.from()
javascript
function demo() {
const arr = Array.from(arguments);
console.log(Array.isArray(arr)); // true
}
demo(1, 2, 3);2. Via the spread operator (...)
javascript
function demo() {
const arr = [...arguments];
console.log(arr); // [1, 2, 3]
}
demo(1, 2, 3);3. Via slice.call()
javascript
function demo() {
const arr = Array.prototype.slice.call(arguments);
console.log(arr); // [1, 2, 3]
}
demo(1, 2, 3);Short version:
| Property | Array-like object | Real array |
|---|---|---|
| Has numeric indices | Yes | Yes |
Has length | Yes | Yes |
Has methods (map, push, filter) | No | Yes |
Array.isArray() returns true | No | Yes |
Examples of array-like objects in JavaScript:
| Source | Type |
|---|---|
arguments | array-like object of function arguments |
document.querySelectorAll() | NodeList |
document.getElementsByClassName() | HTMLCollection |
FileList | list of files from <input type="file"> |
Conclusion: An array-like object is an object similar to an array in structure (
indices + length), but without array methods.To work with it like a regular array, you can convert it using
Array.from()or[...spread].
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.