JS: Array Length Property

By Xah Lee. Date: .

Length special property

Every array object has a special property key "length". It is the object's own property, and is a key of type string. The “length” property is automatically updated when array elements are added or removed using Array.prototype methods.

Array length can be set. If you set it, the array will be lengthened or shortened.

Own property

// every array has its own property length
console.assert(
 Object.hasOwn(["a", "b"], "length"),
);

Setting length creates sparse array or truncate

// creating a sparse array by setting the length property

const xx = ["a", "b"];

// set the length property beyond the last index
xx.length = 5;

console.log(Object.getOwnPropertyNames(xx));
// [ "0", "1", "length" ]

console.log(xx);
// [ "a", "b", <3 empty items> ]
// truncating a array by setting the length

const xx = [1, 2, 3, 4, 5];

console.log(Object.getOwnPropertyNames(xx));
// [ "0", "1", "2", "3", "4", "length" ]

xx.length = 1;

// index 1 doesnt exist
console.log(xx[1]);

console.log(Object.getOwnPropertyNames(xx));
// [ "0", "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);