Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Array indexing syntax in JavaScript

Use square brackets to read and write zero-based array elements. Whether a key is an array index affects `length`, and a missing element is not the same as a stored `undefined`.

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

Syntax

array[indexExpression]
array[indexExpression] = value
delete array[indexExpression]

Array indexing syntax uses a[i] to read a property and a[i] = value to write it. JavaScript evaluates the expression i and converts the result to a property key: a string or a Symbol. Ordinary Array indices start at zero: a[0] and a["0"] refer to the same property.

An array index is the standard decimal spelling of an integer from 0 through 2³² − 2, with no extra leading zeros. The keys "01" and "-1" are not array indices, so writing to them does not change length. a[-1] looks up the property "-1"; use a.at(-1) to read the last position if the runtime supports the method. Out of bounds, at() returns undefined without looking up the property at the computed index.

Bracket reads also look up the prototype chain. If the key is absent throughout the chain, the result is undefined, not a bounds error. Use Object.hasOwn(a, i) to distinguish a hole (no own element at that index) from an own element whose value is undefined.

If a write creates an own element at or beyond length, the new length is the index plus one. Skipped positions remain holes if they have no own elements. delete a[i] neither shifts elements nor reduces length, even when deletion succeeds.

Examples

{
  const a = ["A"];
  a["01"] = "label";
  a[-1] = "tag";
  console.log(`${a[0]} ${a["0"]} ${a["01"]} ${a.length}`);

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

  delete a[4];
  console.log(`${Object.hasOwn(a, 4)} ${a.length}`);
}

Result

A A label 1
tag E 5
undefined false undefined true
false 5

Compare `a[-1]` with `a.at(-1)`. Positions `1` and `3` both read as `undefined`, but only `3` is an own element. Deleting element `4` does not change `length`.

Related lessons

  • JavaScript · Lesson 21 · Advanced · Version: 4

Sources