DEV Community

Muhammad Saim Hashmi
Muhammad Saim Hashmi

Posted on

1

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay