Open In App

TypeScript Array.prototype.at() Method

The at() function is a feature in TypeScript that allows you to access elements in an array using positive and negative, both kinds of indices. It will return the stored value at the given index in case of a positive number and start retrieving the values from the end in the case of negative values.

Syntax:

array.at(index: number): T | undefined

Parameter:

Return Value:

Returns the element which is stored at the given index position. If the given index position is invalid then it will return undefined.



Example 1: The below code will demonstrate that how to access elements by passing valid negative and positive both kinds of indices as parameters.




const geeks: (number | string | boolean)[] =
["GeeksforGeeks", 2, "TypeScript", true];
 
console.log(
    "Passed index is 1, will return 2nd element: ", geeks.at(1));
console.log(
    "Passed index is -1, will return last value element: ", geeks.at(-1));
console.log(
    "Passed index is 2, will return 3rd element: ", geeks.at(2));

Output:



Passed index is 1, will return 2nd element: 2
Passed index is -1, will return last value element: true
Passed index is 2, will return 3rd element: TypeScript

Example 2: The below code will show the behavior of the at() method if we pass an invalid index position as parameter to it.




const geeks: (number | string | boolean)[] =
["GeeksforGeeks", 2, "TypeScript", true];
 
console.log(
    "Passed invalid index as -5: ", geeks.at(-5));
console.log(
    "Passed invalid index as 6: ", geeks.at(6));
console.log(
    "Passed invalid index as -7: ", geeks.at(-7));

Output:

Passed invalid index as -5: undefined
Passed invalid index as 6: undefined
Passed invalid index as -7: undefined
Article Tags :