how sum all array element with while loop 1

how sum all array element with while loop

// define a list
const list = [1,2,3,4,5];

// arrow function to sum array element
const result2 = () => {
  var i = list.length;
  var sum = 0;
  while (i--) {
    sum += list[i]
  }
  console.log(sum)
}
result2()

Here is what the above code is Doing:
1. Define a list
2. Define an arrow function
3. Define a variable i and set it to the length of the list
4. Define a variable sum and set it to 0
5. While i is greater than 0, subtract 1 from i and add the value of list[i] to sum
6. Print the value of sum
7. Call the function

Similar Posts