Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
How to access the last element of an array using destructuring?

Suppose I have an array like this: [2, 4, 6, 8, 10].

I want to access the first and last element of this array using destructuring, currently I'm doing this:

const array = [2, 4, 6, 8, 10];
const [first, , , , last] = array;
console.log(first, last);

But this is only works with arrays of length 5 and is not generic enough.

In Python I could do something like this:

array = [2, 4, 6, 8, 10]
first, *mid, last = array
print(first, last)

But in JS this is not possible since rest elements should be the last. So, is there some way to do this in JS or this is not possible?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use object destructuring and grab the 0 key (which is the first element) and rename it to first & then using computed property names you can grab the array.length - 1 key (which is the last element) and rename it to last.

const array = [2, 4, 6, 8, 10];
const { 0: first, [array.length - 1]: last } = array;
console.log(first, last);

You can also grab the length via destructuring and then use that to grab the last element.

const array = [2, 4, 6, 8, 10];
const { length, 0: first, [length - 1]: last } = array;
console.log(first, last);

Another simple approach to access the last element would be to use the Array.prototype.at method. This is not related to destructuring but it's worth knowing.

const array = [2, 4, 6, 8, 10];
console.log(array.at(-1));

about 4 years ago · Juan Pablo Isaza Report

0

Not necessarily using destructuring, but still concise in my opinion:

const arr = [1, 2, 3, 4, 5];
const [ first, last ] = [ arr.at(0), arr.at(-1) ];

console.log(first, last);

about 4 years ago · Juan Pablo Isaza Report

0

No, you can't use destructuring like that without convoluted workarounds.
A shorter, more readable alternative is to just pop:

const array = [2, 4, 6, 8, 10];
const [first, ...middle] = array;
const last = middle.pop();

console.log(first, middle, last);

Or, just access them by index:

const array = [2, 4, 6, 8, 10];
const first = array[0];
const last = array[array.length - 1];

console.log(first, last);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!