JavaScript: What's Array-Like Object?

By Xah Lee. Date: . Last updated: .

What is a array-like object?

A object such that:

  1. has property names of consecutive non-negative integers {0, 1, 2, …}.
  2. has a property length with a value that's the number of these properties.
  3. is not a true array. That is, Array.isArray(obj) returns false.

〔►see JavaScript: Understand JS Array

What is the difference between true array object and array-like object?

For a true array, value of length will automatically change. For array-like object, value of length will not automatically change.

// create a array-like object
var a1 = {0:"a", 1:"b" , length:2};
a1[2] = 99;
console.log(a1.length) // 2
// length would be 3 if it's a true array

// real array
var a2 = ["a", "b"];
a2[2] = 99;
console.log(a2.length) // 3

Real array object's parent is Array.prototype, therefore, it has methods such as map.

〔►see JavaScript: Prototype and Inheritance

〔►see JavaScript: Array.prototype

Array-like object's parent (if it has a parent) is not Array.prototype. Therefore, you cannot call array methods directly as in obj.map(…).

But you can call array methods on array-like object like this: Array.prototype.methodName.call(array-like_object, …).

〔►see JavaScript: Function Call, Apply, Bind

〔►see JavaScript: How to Convert Array-Like Object to Array?

How to check if a object is true array?

Array.isArray(obj)

Where does array-like object came from?

In DOM, method such as document.getElementsByClassName returns the object NodeList or HTMLCollection, and they are array-like objects.

JavaScript's arguments object is a array-like object.

〔►see JavaScript: Function's “arguments” Object

// “arguments” inside function is a predefined array-like object

function ff(x,y) {
    console.log(arguments.length);
    console.log(arguments[0]);
    console.log(arguments[1]);
    console.log(Array.isArray(arguments));
    console.log(Object.getOwnPropertyNames(arguments));
}

ff("a", "b");

// prints

// 2
// a
// b
// false
// [ '0', '1', 'length', 'callee' ]

How to convert array-like object to array?

JavaScript: How to Convert a Array-Like Object to Array?

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: What's Array-Like Object?
  6. JavaScript: How to Convert Array-Like Object to Array?
  7. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.