DEV Community

Muhammad Saim Hashmi
Muhammad Saim Hashmi

Posted on

 

Last Index Value Of Array Javascript/TypeScript

Hey everyone, I usually give thought to how can I make my and other's life easy, so came up with the idea to write articles.
Getting to the point, I came across a life hack for arrays. Finding the last index value in an array was always like using the array's length and subtracting 1 from it(As the array gives length like normal daily like counting, whereas arrays start with 0 indexes).

Example

let array = [3,4,5,6,7];
let lastElement = array[array.length - 1];
console.log(lastElement); // prints 7
Enter fullscreen mode Exit fullscreen mode

So whats the way around? Here it is 😁😁

let array = [3,4,5,6,7];
let lastElement = array.at(-1);
console.log(lastElement); //prints 7
Enter fullscreen mode Exit fullscreen mode

Additionally
Just keep going reverse, you can get all elements of the array. Don't forget a condition to avoid going out of indexes as it'll give you undefined.

Feel free to comment to add more information to this article. Happy Coding.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post