0

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);
    }
  }
}
1
  • You are repeating while array has a length. You never reduce length of the array. Commented Feb 6, 2022 at 7:50

2 Answers 2

1

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();

Sign up to request clarification or add additional context in comments.

Comments

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());

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.