In this article, you’ll learn about Javascript built-in Array.at()
method. In JavaScript, you can use the square bracket notation([]
) to access an element at a specific index of an array. For instance, the arr[0]
returns the first element in the array arr
, the arr[3]
returns the fourth element, and so on.
And To get the last element in an array, you use the length property like this:
arr[arr.length-1]
But you can’t use the negative integer with square bracket notation if you used the negative integer with square bracket notation([]
), it returns undefined
. To overcome this issue, ES2022 introduced a new method at()
added to the prototype of Array, String, and TypeArray.
Array.prototype.at()
method used to get the element of the specific index. undefined
. Here are some examples of Array.at()
method:
let arr = ["Java", "Javascript", "Python", "C#", "ReactJs", "Angular", "Flutter"];
console.log(arr.at(1));
// Output => "Javascript"
console.log(arr.at(5));
// Output => "Angular"
/*
If the value passes as an argument that is bigger or equal
to the array length, then, like the regular accessor,
the method returns undefined. For Example
*/
console.log(arr.at(50));
// Output => undefined
/*
If you pass a negative integer as an argument,
then this method counts back from the last item
in the array. this is not possible with the
Square bracket Notation([]). For Example
*/
console.log(arr.at(-1));
// Output => "Flutter"
console.log(arr.at(-3));
// Output => "ReactJs"
I hope this article will help you to understand Javascript built-in Array.at()
method.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments