-2

I want to get the elements of the array and sum them. I don’t know why but it just takes the first 6 variables. What do I need to do?

function range(start, end) {
  let arr = []

  for (let i = start; i <= end; i++) {
    arr.push(i)
  }

  return arr
}

let arr = range(1, 10)

function sum() {
  let g = 0;

  for (let i = 0; i <= arr.length; i++) {
    g += arr.shift()
  }

  return g
}

console.log(sum())
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
fpbidni
  • 11
  • 1
  • 1
    Learn about [how to debug small programs](//ericlippert.com/2014/03/05/how-to-debug-small-programs). Try using your browser’s [debug capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). – Sebastian Simon Dec 30 '22 at 21:49

1 Answers1

2

In your sum function -

function sum() { // ❌ no input parameter
  let g = 0;

  for (let i = 0; i <= arr.length; i++) { // ❌ i will go out of bounds
    g += arr.shift() // ❌ arr.shift modifies the length of arr
  }

  return g
}

Let's see what happens given a concrete example arr -

const arr = [1,2,3,4,5,6,7,8,9]

for (let i = 0; i <= arr.length; i++) {
  g += arr.shift()
}
i arr i <= arr.length arr.shift() g
0 [1,2,3,4,5,6,7,8,9] true 1 1
1 [2,3,4,5,6,7,8,9] true 2 3
2 [3,4,5,6,7,8,9] true 3 6
3 [4,5,6,7,8,9] true 4 10
4 [5,6,7,8,9] true 5 15
5 [6,7,8,9] false exit loop 15 ❌

As you can see, i exceeds the length of the array after the halfway point has been reached. g is only equal to the sum of the first half. To fix it, don't modify the array inside the loop -

function sum(arr) { // ✅ input parameter
  let g = 0;

  for (let i = 0; i < arr.length; i++) { // ✅ use <
    g += arr[i] // ✅ arr[i] reads element, doesn't modify arr
  }

  return g
}
i arr i < arr.length arr[i] g
0 [1,2,3,4,5,6,7,8,9] true 1 1
1 [1,2,3,4,5,6,7,8,9] true 2 3
2 [1,2,3,4,5,6,7,8,9] true 3 6
3 [1,2,3,4,5,6,7,8,9] true 4 10
4 [1,2,3,4,5,6,7,8,9] true 5 15
5 [1,2,3,4,5,6,7,8,9] true 6 21
6 [1,2,3,4,5,6,7,8,9] true 7 28
7 [1,2,3,4,5,6,7,8,9] true 8 36
8 [1,2,3,4,5,6,7,8,9] true 9 45
9 [1,2,3,4,5,6,7,8,9] false exit loop 45 ✅
Mulan
  • 129,518
  • 31
  • 228
  • 259