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

81
Views
Destructuring array elements inside the for loop in javascript

Let's assume that I have a code structure as below,

const fruits = [ `apple`, `banana`, `orange` ];

for ( let i = 0; i < fruits.length; i++ ) {

    const res = fruits[ i ];
    console.log ( res ); // apple banana orange
}

I want to destructure the

const res = fruits[ i ];

Is it possible and I can use forEach to achieve the destructuring but I want to achieve the same using the for loop.

Thanks in advance.

PS: using forEach or for..in it can be done but I want to get same destructuring within the for loop.

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

0

If you absolutely want to keep the classic for loop:

const fruits = [`apple`, `banana`, `orange`];

for (let i = 0; i < fruits.length; i++) {
    const { [i]: res } = fruits;
    console.log(res); // apple banana orange
}

As a shorter syntax, for..of works with iterable objects (like arrays).

You can use it like this:

const fruits = [`apple`, `banana`, `orange`];

for (const fruit of fruits) {
    console.log(fruit); // apple banana orange
}

To go further, you can even use destructuring in a for..of loop (e.g: to retrieve the string lengths):

const fruits = [`apple`, `banana`, `orange`];

for (const { length } of fruits) {
    console.log(length); // 5 6 6
}

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!