JavaScript Array at() Method is used to access an element from an array by its index. It provides a convenient way to retrieve elements from both the beginning and the end of an array.
Normally, JavaScript developers use square bracket notation ([]) to access array elements. For example, numbers[0] returns the first element, while numbers[numbers.length - 1] returns the last element.
However, accessing the last element using the array’s length can make code longer. The at() method simplifies this process by allowing negative indexes. For example, numbers.at(-1) returns the last element.
The at() method is also available on strings and several other indexed collections.
Syntax and Formal Specification
The method signature is at(index).
Parameters
index— The zero-based index of the element to return, converted to an integer. If negative, the accessed index isindex + array.length. Non-integer values are truncated toward zero (e.g.,1.9becomes1,-1.9becomes-1) .
Return Value
The element at the resolved index, or undefined if the resolved index falls outside [0, array.length - 1] .
Basic Example of JavaScript at() Method
The following example demonstrates how to retrieve an array element using at().
const fruits = ["Apple", "Banana", "Mango", "Orange"];
const result = fruits.at(2);
console.log(result);
Output:
Mango
In this example, at(2) retrieves the element at index 2. Since JavaScript array indexes start at zero, the third element is "Mango".
at() vs with(): Reading and Writing with Negative Indices
at() reads using negative indices. Its companion method with() (ES2023) writes using negative indices, returning a new array with the specified index replaced. Together, they provide a complete negative-index API for reading and writing .
const arr = [1, 2, 3, 4, 5]; // Read with negative index console.log(arr.at(-1)); // 5 // Write with negative index (returns a new array) const updated = arr.with(-1, 99); console.log(updated); // [1, 2, 3, 4, 99] console.log(arr); // [1, 2, 3, 4, 5] (unchanged)
at() itself never mutates the array. It is a pure read operation.
at() vs slice(-1)[0]
A common pre-ES2022 pattern for accessing the last element was arr.slice(-1)[0]. This allocates a new single-element array just to extract its only value. at() avoids this allocation entirely, making it strictly more efficient for the same task :
const arr = [1, 2, 3]; // Allocates a temporary array const viaSlice = arr.slice(-1)[0]; // No allocation const viaAt = arr.at(-1); console.log(viaSlice, viaAt); // 3 3
at() vs arr[arr.length - 1]
Both are O(1) and perform a single property access. The difference is purely ergonomic. at() is preferred for readability, especially when the array reference is long or the expression is nested:
// Verbose const last = someNestedObject.data.items[someNestedObject.data.items.length - 1]; // Concise const last = someNestedObject.data.items.at(-1);
In microbenchmarks, the performance difference between the two is negligible. Modern engines optimize both to the same fast path.
Safe Last-Element Access
at() returns undefined for empty arrays, making it safe to use without length checks:
const empty = []; console.log(empty.at(-1)); // undefined (no error) console.log(empty.at(0)); // undefined
This is more robust than arr[arr.length - 1], which also returns undefined for empty arrays but requires the length calculation.
Conditional Last-Element Processing
A common pattern—checking whether an array has content before accessing the tail:
function processLast(items) { const last = items.at(-1); if (last === undefined && items.length === 0) { return "Empty"; } return `Processing: ${last}`; } console.log(processLast(["a", "b"])); // "Processing: b" console.log(processLast([])); // "Empty"
Careful: if the array legitimately contains undefined as its last element, at(-1) returns undefined and is indistinguishable from “empty” unless length is also checked.
Understanding How at() Converts the Index Value
The at() method accepts an index value and converts it into an integer before accessing an array element. This means the argument does not always need to be a whole number.
JavaScript performs an integer conversion when processing the index. Decimal values are truncated toward zero rather than rounded to the nearest integer.
Consider the following example:
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.at(1.8));
console.log(numbers.at(2.9));
console.log(numbers.at(-1.7));
console.log(numbers.at(-2.9));
Output:
20
30
50
40
In this example:
1.8becomes1.2.9becomes2.-1.7becomes-1.-2.9becomes-2.
This behavior is important when an index comes from calculations or user input. If your application expects only whole-number indexes, validate the input before passing it to at().
Using at() with String Index Values
The at() method can also receive numeric values represented as strings. JavaScript converts a valid numeric string into a number during index processing.
const languages = ["JavaScript", "Python", "Java", "PHP"];
console.log(languages.at("0"));
console.log(languages.at("2"));
console.log(languages.at("-1"));
Output:
JavaScript
Java
PHP
Although this works, passing numbers directly is generally clearer and easier to maintain.
For example:
const index = 2;
const result = languages.at(index);
console.log(result);
Output:
Java
If the index comes from an HTML input field, remember that input values are usually strings. You can convert the value explicitly using Number() and validate it before accessing the array.
Understanding NaN, Infinity, and Undefined Indexes
The at() method also handles special numeric values according to JavaScript’s integer conversion rules.
For example, NaN is converted to zero. An undefined index is also converted to zero, while positive and negative infinity cannot identify a valid array position.
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.at(NaN));
console.log(fruits.at(undefined));
console.log(fruits.at(Infinity));
console.log(fruits.at(-Infinity));
Output:
Apple
Apple
undefined
undefined
The first two expressions return the element at index 0. The infinity values return undefined because they do not represent valid finite positions in the array.
This behavior can be surprising when an index variable is calculated dynamically. Checking the input before calling at() helps avoid unexpected results.
Using at() with Dynamic Array Updates
Arrays frequently change while an application is running. New elements may be added with push(), or existing elements may be removed with pop().
Because at() reads the array’s current contents, its result changes when the array changes.
const tasks = ["Design", "Development", "Testing"];
console.log(tasks.at(-1));
tasks.push("Deployment");
console.log(tasks.at(-1));
tasks.pop();
console.log(tasks.at(-1));
Output:
Testing
Deployment
Testing
Initially, "Testing" is the last element. After push() adds "Deployment", the last element changes. When pop() removes that element, "Testing" becomes the last item again.
The at() method does not maintain a permanent reference to the last position. It calculates the requested position from the array’s current length whenever the method is called.
Using at() Inside a Reusable Function
If your application needs to retrieve the last element from multiple arrays, you can create a reusable function.
function getLastElement(array) {
return array.at(-1);
}
const numbers = [10, 20, 30];
const names = ["Rahim", "Karim", "Sakib"];
const countries = ["Bangladesh", "India", "Japan"];
console.log(getLastElement(numbers));
console.log(getLastElement(names));
console.log(getLastElement(countries));
Output:
30
Sakib
Japan
The function accepts an array and returns its final element. This avoids repeating the same indexing expression throughout your application.
You can also provide a fallback value when the array is empty:
function getLastElement(array) {
return array.at(-1) ?? "No items available";
}
console.log(getLastElement([10, 20, 30]));
console.log(getLastElement([]));
Output:
30
No items available
The nullish coalescing operator (??) returns the fallback only when the result is null or undefined. This means valid values such as 0, false, and an empty string are preserved.
Using at() with the arguments Object
Inside a traditional JavaScript function, the arguments object contains the values passed to that function. It is array-like, but it is not a real array.
Because Array.prototype.at() is generic, it can retrieve values from the arguments object.
function displayArguments() {
console.log(Array.prototype.at.call(arguments, 0));
console.log(Array.prototype.at.call(arguments, -1));
}
displayArguments("JavaScript", "Python", "PHP");
Output:
JavaScript
PHP
The first call retrieves the first argument, while the second call retrieves the last argument.
In modern JavaScript, rest parameters are often preferred because they create a real array:
function displayLanguages(...languages) {
console.log(languages.at(0));
console.log(languages.at(-1));
}
displayLanguages("JavaScript", "Python", "PHP");
Output:
JavaScript
PHP
Using rest parameters allows you to work with standard array methods directly.