Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda