JavaScript Tutorials

JavaScript Array at()
Syntax & Examples

Array.at() method

The at() method of the Array class in JavaScript returns the array item at the given index. It accepts negative integers, which count back from the last item in the array.


Syntax of Array.at()

The syntax of Array.at() method is:

at(index)

This at() method of Array returns the array item at the given index. Accepts negative integers, which count back from the last item.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the item to retrieve. Negative integers count back from the last item in the array.

Return Type

Array.at() returns value of type Any.



✐ Examples

1 Using at() method to get an item at a specific index

In JavaScript, we can use the at() method to retrieve an item at a specific index in an array.

For example,

  1. We define an array variable arr with elements [10, 20, 30, 40, 50].
  2. We use the at() method with index 2 to retrieve the item at that index.
  3. The item at index 2, which is 30, is stored in the variable itemAtIndex2.
  4. We log itemAtIndex2 to the console using console.log() method.

JavaScript Program

const arr = [10, 20, 30, 40, 50];
const itemAtIndex2 = arr.at(2);
console.log(itemAtIndex2);

Output

30

2 Using at() method to get the last item

In JavaScript, we can use at() method to get the last item in the array using index = -1.

For example,

  1. We define an array variable arr with elements ['apple', 'banana', 'cherry'].
  2. We use the at() method with index -1 to retrieve the last item.
  3. The last item, which is 'cherry', is stored in the variable lastItem.
  4. We log lastItem to the console using console.log() method.

JavaScript Program

const arr = ['apple', 'banana', 'cherry'];
const lastItem = arr.at(-1);
console.log(lastItem);

Output

cherry

3 Using at() method to get the first item

In JavaScript, we can use at() method to get the first item in the array using index = 0.

For example,

  1. We define an array variable arr with elements [true, false, true, false].
  2. We use the at() method with index 0 to retrieve the first item.
  3. The first item, which is true, is stored in the variable firstItem.
  4. We log firstItem to the console using console.log() method.

JavaScript Program

const arr = [true, false, true, false];
const firstItem = arr.at(0);
console.log(firstItem);

Output

true

Summary

In this JavaScript tutorial, we learned about at() method of Array: the syntax and few working examples with output and detailed explanation for each example.