From 4d86c05c09f220daa9585048c458a24e81d4e811 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Tue, 16 Aug 2022 10:08:03 +0300 Subject: [PATCH] Add tip for last JS array element --- blog_posts/js-last-element-of-array.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 blog_posts/js-last-element-of-array.md diff --git a/blog_posts/js-last-element-of-array.md b/blog_posts/js-last-element-of-array.md new file mode 100644 index 000000000..bbb8c429a --- /dev/null +++ b/blog_posts/js-last-element-of-array.md @@ -0,0 +1,25 @@ +--- +title: "Tip: Get the last element of a JavaScript array" +shortTitle: Last element of array +type: tip +tags: javascript,array +expertise: beginner +author: chalarangelo +cover: blog_images/purple-laptop.jpg +excerpt: Array destructuring can be leveraged in many different ways. Here's one of them. +firstSeen: 2022-08-28T05:00:00-04:00 +--- + +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. + +```js +const arr = [1, 2, 3]; +const { 0: first, length, [length - 1]: last } = arr; +first; // 1 +last; // 3 +length; // 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 doesn't have any significant performance advantages over other options, such as using `Array.prototype.slice()`.