Destructure First And Last Element Of Array
Extracting the first and last items in a JavaScript array should be easier.
const { 0: first, length: _, [_ - 1]: last } = [ 1, 2, 3, 4, 5 ];
Of course _
is also bound to the length of the array, so doing this more than once will require another variable. Doing this more than once will also require unique variables in place of first
and last
.
Alternatively you can move the destructuring into a function.
const ends = ({ 0: first, length: _, [_ - 1]: last }) => [ first, last ];
const [ first, last ] = ends([ 1, 2, 3, 4, 5 ]);
I don't love the name ends
, so name it whatever you want. The only other name that popped into my head was firstLast
, which isn't that great either.