JS: Array.prototype.length

By Xah Lee. Date: . Last updated: .

Length

xArray.length

for true array, value is the number of elements.

  • for Sparse Array, just return value of length that was set to.
  • for Array-Like Object, value is the value of its own property key β€œlength”.

πŸ›‘ warning: Array length can be set. If you set it, the array becomes Sparse Array.

console.log([3, 4].length);
// 2
// set the length property results in sparse array
const xx = [3, 4];
xx.length = 5;
console.log(xx);
// [ 3, 4, <3 empty items> ]
// create array-like object
let xx = { length: 9 };

// length is whatever the property's value
console.log(xx.length);
// 9

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,
);
// test trying to delete the property length of array
const xx = [3, 4];
console.assert(Object.hasOwn(xx, "length") === true);
console.assert(Reflect.deleteProperty(xx, "length") === false);
console.assert(xx.length === 2);

Array-like object length property

by definition Array-like object is a object with own length property. its value can be any integer.

// create array-like object
let xx = { length: 9 };