Negative index

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Array/String .at() Method

JS · Modern Features
Syntax
arr.at(index)
str.at(index)
Example
const stack = ["first", "second", "third", "last"];
console.log(stack.at(0));   // "first"
console.log(stack.at(-1));  // "last"
console.log(stack.at(-2));  // "third"

console.log("hello".at(-1)); // "o"

Note Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.

PYPython

Indexing & Negative Indexing

PY · Lists
Syntax
items[index]
items[-index]
Example
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
Output
apple
date
cherry

Note Index 0 is the first element, -1 is the last. Accessing an index beyond the list length raises IndexError.

Frequently asked questions

How does JavaScript handle negative index?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Array/String .at() Method" snippet in JavaScript uses `arr.at(index)`.
Which code does the JavaScript example use?
The "Array/String .at() Method" snippet uses `arr.at(index)`, from the Modern Features section of the JavaScript cheat sheet.
Which stacks cover "negative index" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Array/String .at() Method": Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.