Negative array subscript
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]Why not .at(-x) and .with(-x, value)?
Section titled “Why not .at(-x) and .with(-x, value)?”- The
.at()method can retrieve elements from the end, but it doesn’t allow writes via negative subscripts. - We shouldn’t have two different ways of indexing with negative subscripts.
Support
Section titled “Support”This syntax already exists in JavaScript
JavaScript and TypeScript
Section titled “JavaScript and TypeScript”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.