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

112
Vistas
How to explain reversing an array in JavaScript using for loops

I need help with understanding how this code works. task: Without using functions, you must reverse all items in a list. That is, redo it back and forth.

Example: Input: [-89,71,11,0,4,6] Output: [6,4,0,11,71,-89]

I found this example, but I need to explain how it works and be able to explain all aspects of the code:

let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = arr[i];
  arr[i] = arr[n-i];
  arr[n-i] = temp;
}
console.log(arr);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use much simpler like:

const arr = [1, 2, 3, 4, 5]
const reversedArr = []

for (let i = arr.length - 1; i >= 0; i--) {
  reversedArr.push(arr[i])
}

console.log(reversedArr)

Explanation is just, iterating over each item in the original array, but starting from the last item (arr.length = 5 here) and push each of them to a new array.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The code is just doing a reverse function.

The let temp = arr[i];arr[i] = arr[n-i];arr[n-i] = temp; is trying to switch the sequence between the i item and the i item from the last element,.

In your code, n is the last element.

Example, i =0, temp will equal to be the first element in arr which is 1, and arr[n-i] will be the last i element (the last element) which is 7.

Then, the code set arr[i] (first element in arr) to the last element value arr[n-i] which is 7.

Finally, the code assign the value of the arr[n-1] (last element in arr) to temp which is 1 and the first element in arr .

So you successfully reverse the first and last element and the loop keep doing the same thing when i=1,2......

let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = arr[i];
  arr[i] = arr[n-i];
  arr[n-i] = temp;
}
console.log(arr);

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