Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Array length and indexing in JavaScript

An array’s `length` sets its index boundary; it does not count elements. Learn how indexed writes change that boundary and how to tell a hole from `undefined`.

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

Syntax

a.length; a[i]; a[i] = value; a.length = n; delete a[i]; Object.hasOwn(a, i); a.at(i);

Array.length/indexing covers how an array’s length and its zero-based element indices work together. a.length is an own property, writable by default but non-configurable. Its value is an integer from 0 to 2 ** 32 - 1. It is the exclusive upper bound for own element indices, not a count of elements. By contrast, Array.length describes the constructor function’s expected parameter count, not the length of an array.

Brackets perform property access: a[1] and a["1"] use the same key. Array indices are the canonical decimal spellings of integers from 0 to 2 ** 32 - 2. Keys such as "01", "-1", and "4294967295" are not array indices and do not affect length. a[-1] looks up "-1"; a.at(-1) reads the last position of a nonempty array. If the computed index is out of bounds, at() returns undefined without looking up that property.

Creating an own element at i >= a.length extends length to i + 1, leaving any skipped positions as holes. A hole has no own property; reading it gives undefined unless a value is inherited. Use Object.hasOwn(a, i) to distinguish a hole from an own element set to undefined. A successful delete a[i] removes an element without shortening the array.

Increasing length adds holes; reducing it deletes own elements at or above the new boundary. If length is writable, assigning a Number that is not an integer or is outside the allowed range throws RangeError. Assigning a BigInt instead throws TypeError during conversion, before the range check. A non-configurable element can block truncation: higher elements may already have been deleted, and length stops at the blocking index plus one. In strict mode, that failed assignment throws TypeError.

Examples

{
  const a = ["A"];
  a[3] = "D";
  a[2] = undefined;
  a[-1] = "tag";

  console.log(`length: ${a.length}`);
  console.log(`1: ${a[1]}, own: ${Object.hasOwn(a, 1)}`);
  console.log(`2: ${a[2]}, own: ${Object.hasOwn(a, 2)}`);
  console.log(`[-1]: ${a[-1]}, at(-1): ${a.at(-1)}`);

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

Result

length: 4
1: undefined, own: false
2: undefined, own: true
[-1]: tag, at(-1): D
length: 4, own 3: false, [-1]: tag

Both `1` and `2` read as `undefined`, but only `2` is an own element. Growing the array again does not restore element `3`; the property `"-1"` remains.

Related lessons

  • JavaScript · Lesson 41 · Advanced · Version: 4

Sources