JavaScript Array.at() Method

The JavaScript Array at() method is used to retrieve an element at a specified index from an array. Unlike the traditional method of accessing elements using bracket notation (array[index]), the Array.at() method allows negative indices, making it easier to retrieve elements from the end of the array without having to calculate the index manually.

For example, array.at(-1) will return the last element of the array, which is a significant improvement over using array[array.length - 1]. This method is a new addition to the JavaScript language, introduced in ECMAScript 2022.

Syntax

The syntax for the Array.at() method is given below:

plaintext
array.at(index)

Parameters

The Array.at() method accepts a single parameter:

  • index (Required): The index of the element to return. A positive index retrieves elements from the start of the array (starting at 0), while a negative index counts back from the end of the array.

Examples:

  • array.at(0) returns the first element.
  • array.at(-1) returns the last element.

Return Value

The value of the element at the specified index. If the provided index is out of range (i.e., greater than or less than the array length), undefined is returned.

Examples of JavaScript Array at() Method

Example 1: Accessing Elements with Positive Indices

You can use Array.at() method to access elements in an array by passing a positive index.

javascript
const arr = [ 10, 20, 30, 40, 50 ];
console.log(arr.at(0));
console.log(arr.at(1));
console.log(arr.at(3));
console.log(arr.at(10));

Explanation: In this example, we access elements at index positions 0, 1, and 3. Since the index 10 is out of range, undefined is returned.

Example 2: Accessing Elements with Negative Indices

Using negative indices allows you to retrieve elements starting from the end of the array.

javascript
const arr = [ 10, 20, 30, 40, 50 ];
console.log(arr.at(-1));
console.log(arr.at(-2));
console.log(arr.at(-4));
console.log(arr.at(-10));

Explanation: In this example, we retrieve elements starting from the end using negative indices. The arr.at(-1) returns the last element of array, while arr.at(-2) returns the second last element. The index -10 is out of range, so it returns undefined.

Example 3: Using Array.at() with Empty Arrays

If you use the Array.at() method on an empty array, it will always return undefined for any index, whether positive or negative.

javascript
const arr = [];
console.log(arr.at(0));
console.log(arr.at(-1));

Explanation: Since the array is empty, there are no elements to retrieve, so undefined is returned regardless of the index provided.

JavaScript

1873

347

Related Articles