Skip to content

Latest commit

 

History

History
33 lines (25 loc) · 882 Bytes

pick-the-first-and-last-items-of-an-array.md

File metadata and controls

33 lines (25 loc) · 882 Bytes
title category date topics metadata
Pick the first and last items of an array
Tip
2021-05-17 20:37:00 +7
JavaScript
image
pick-first-last.png

If you want to receive the first and last items of a given array, you might think of the common way as following:

const length = arr.length;
const first = arr[0];
const last = arr[arr.length - 1];

Because an array is also an object, the length property can be accessed with the destructuring syntax:

const { length } = arr;

Also, an array item at any position can be accessed with its index. Hence, we can shorten three lines at the top with a single line:

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

See also