Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 23, 2022 03:56 am GMT

Tips: How to get last element of an array in javascipt

An array is a data structure, which can store a fixed-size collection of elements of the same data type

If you have worked with JavaScript arrays before, you might know that they can be destructured much like objects. This is most commonly used to extract the first value of an array or the values of an array with a known length.

But destructuring can go much further, as it allows you to extract the length property of an array. Add this to the fact that extracted variables can be used in the destructuring assignment itself and you can put together a one-liner to extract the last element of an array.

const arr = [1, 2, 3];const { 0: first, length, [length - 1]: last } = arr;first; // 1last; // 3length; // 3

While this technique is interesting, it has a couple of caveats. First off, you have to extract the length property, which creates an additional variable for it. And secondly, it doesnt have any significant performance advantages over other options, such as using Array.prototype.slice().

Another way we can do is, first we need array length then subtract 1 to get the last element index.

Take a loot at code

const arr = [1, 2, 3];const lastEle = arr[arr.length - 1]lastEle; // 3

arr.length = 3
3 1 = 2
arr[2] = 3

website DevvSakib.Me


Original Link: https://dev.to/devvsakib/tips-how-to-get-last-element-of-an-array-in-javascipt-3k2j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To