Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Array length and indexing in JavaScript

An array’s `length` defines its index span, not how many elements are present. Writing a new index can extend the array, while shortening it can delete elements.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

a.length
 a[i]
 a[i] = value
 a.length = newLength
 delete a[i]
 Object.hasOwn(a, i)
 a.at(-1)

Array.length and indexing describes how an Array instance’s own length data property relates to its zero-based positions. a.length is neither a method nor a static property. When the length is nonzero, a.length - 1 identifies the last position, which may be empty. Length ranges from 0 to 2 ** 32 - 1; the largest array index is 2 ** 32 - 2.

a[1] and a["1"] refer to the same property key. a["01"], a[-1], and a[2 ** 32 - 1] use keys that are not array indices, so writing them does not change the length. In contrast, a.at(-1) looks up the last position relative to the length and returns undefined if the length is zero.

When a write creates an own element at i >= a.length, the length grows to i + 1, leaving skipped positions empty. A hole is not an own element containing undefined: a bracket read can find an inherited property, and returns undefined if no matching property exists. Object.hasOwn(a, i) tests for an own property; i in a also checks the prototype chain.

Increasing length creates no elements. Decreasing it deletes own elements at indices at or above the new length, starting with the highest index. Increasing the length again does not restore those elements. A successful delete a[i] does not shorten the array.

Assigning a number outside the allowed range or a non-integer to a writable length throws RangeError. A non-configurable element can block truncation: the length ends up one more than that element’s index, and earlier deletions are not undone. The failed assignment throws TypeError in strict mode; outside strict mode it can fail silently.

Examples

{
  const a = ["A", undefined];
  a[3] = "D";
  console.log(`${a.length} ${a[1]} ${a[2]}`);
  console.log(`${Object.hasOwn(a, 1)} ${Object.hasOwn(a, 2)}`);

  a[-1] = "label";
  console.log(`${a[-1]} ${a.at(-1)} ${a.length}`);

  a.length = 2;
  a.length = 4;
  console.log(`${a.length} ${Object.hasOwn(a, 3)} ${a[-1]}`);
}

Result

4 undefined undefined
true false
label D 4
4 false label

Indices `1` and `2` both read as `undefined`, but only `1` is an own element. The key `-1` holds `label`, whereas `a.at(-1)` gives `D`. Truncation removes `D`; regrowing the array does not restore it or affect the `-1` property.

Related lessons

  • JavaScript · Lesson 28 · Advanced · Version: 4

Sources