JS: Array.prototype.length

By Xah Lee. Date: . Last updated: .

Length

xArray.length

The value is usually the number of elements of array.

console.assert([3, 4].length === 2);

🛑 WARNING: Array length can be set. If you set it, the array becomes Sparse Array.

Length is Own Property

Each array has its own property "length".

console.assert(Object.hasOwn([3, 4], "length"));

Length Property Cannot be Deleted

Each array's own property "length" has Property Attribute configurable false, so you cannot delete it.

// the length property of array has configurable attribute false
console.assert(Reflect.getOwnPropertyDescriptor([3, 4], "length").configurable === false);
// indexes of array are enumerable
console.assert(Reflect.getOwnPropertyDescriptor([3, 4], "0").enumerable === true);

Array-Like Object May Also Have Length Property

// create array-like object
let xx = { 0: "a", 1: "b", length: 2 };
Reflect.defineProperty(xx, "length", { enumerable: false });

console.assert(Object.hasOwn(xx, "length") === true);