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

109
Views
Why forEach won't loop through the entire Array?

When I only use console.log() inside the forEach method it logs all the Array elements, but when I use the .push(array.pop()) inside it, it stops at some of the elements?

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;
   let newArray = [];

   array.forEach((arr) => {
     newArray.push(array.pop())
     console.log(arr) 
   })

  return newArray;
}

console.log(reverseArray(sentence))
// RESULT [
//  "This",
//  "will",
//  "all"
// ]

But here it works

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;

   array.forEach((arr) => {
     console.log(arr) 
   })
}

reverseArray(sentence)
// Now it works
// RESULT
// sense.
// VM94:7 make
// VM94:7 all
// VM94:7 will
// VM94:7 This
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are modifying your array while iterating through it. Instead You should use copy of it like so:

Array.from(array).forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

// another variant for old browsers

array.slice().forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

Or, as you do not need elements in callback, you should use simple for loop

const count = array.length
for (let i=0; i < count i++) {
   newArray.push(array.pop())
   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!