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

156
Views
Sum for array with While loop JS

I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers) But nothing I tried worked... any suggestions? :)

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You don't need the while loop. The for...of loop is going to iterate over the array till its length.

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
      sum += numbers;
  }
  console.log(sum)
}

sumNumbersWhileLoop();

If you want to use while, or reduce, then you can do the following:

function sumNumbersWhileLoop() {
  const array = [1, 5, 4, 6, 7];
  let len = array.length - 1;
  let sum = 0;
  while (len >=0) {
    sum += array[len--];
  }
  console.log(sum);

  // Or use reduce :
  const reduceSum = array.reduce((acc, item) => acc + item, 0);
  console.log(reduceSum);
}

sumNumbersWhileLoop();

about 4 years ago · Juan Pablo Isaza Report

0

You can try this:

function sum(arr, sum) {
    arr = [1, 5, 4, 6, 7];
    sum = 0;
    while (arr.length > 0) {
        sum += arr.pop();
    }
    return sum;
}
console.log(sum());
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!