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

248
Vistas
Variable assignments in negative for loop

A typical reverse for loop:

           for(let i = arr.length - 1, item = arr[i]; i >= 0; i--){
              let item = arr[i];
              do thing with item
            }
   

I was thinking I could remove the brackets by assigning the item variable in the for declaration

           for(let i = arr.length - 1, item = arr[i]; i >= 0; i--)
              do thing with item
   

But it doesn't work and I didn't understand why. Then after some careful look at the code, I realised that the item variable is set only once. So I changed it to

           for(let item, i = arr.length - 1; i >= 0; i--, item = arr[i])
              do thing with item

But now item appears undefined and can't figure out why because the code appears correct

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You aren't assigning an initial value to item. These are not "typical" for loops, but I wouldn't use a loop anyway.

You just want the values of an array, so you can use Array functions:

arr.forEach((item, index) => { 
  // do something with item
}

If you want to handle them in reverse order, there is a reverse function that you can use to flip the ends:

arr.reverse().forEach(() => {})

If you wanted to modify the array, for example by doubling the values in an array of numbers, you can use the map method which functions similarly but it returns values that become an output array.

const doubledArr = arr.map((item) => { return item * 2 });

And a streamlined, reversed doubling:

const doubledReversedArr = arr.map(x => 2*x);

Same effect, less code.

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