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 ✅ |