Skip to content

Negative array subscript

Baseline logo Baseline
Chrome logo Edge logo
Firefox logo Zen logo
Safari logo
Node logo
Bun logo
Deno logo
Cloudflare Workers logo

Index arrays from the last element.

Type TC39 CoreJS Babel Civet JS+
Runtime Stage -1 View via Custom
JS+ TypeScript
const arr = [0, 1, 2];
console.log(arr[-1]); // 2
arr[-2] = 3; // [0, 3, 2]
const arr = [0, 1, 2];
console.log(arr[arr.length - 1]); // 2
arr[arr.length - 2] = 3; // [0, 3, 2]
  1. The .at() method can retrieve elements from the end, but it doesn’t allow writes via negative subscripts.
  2. We shouldn’t have two different ways of indexing with negative subscripts.

This syntax already exists in JavaScript

If you try to index negative subscripts you’ll get a really strange behaviour.

const arr = [0, 1, 2];
console.log(arr[-1]); // undefined
arr[-2] = 3; // [-2: 3, 0, 3, 2]

In JavaScript arrays are objects, and values inside square brackets are coerced into strings, different subscripts than numbers will evaluate the same as accessing an object with bracket notation.