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

115
Views
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 answers
Answer question

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 Report

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 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!