Iterate Through an Array with a For Loop

Hi I’ve got the right code for this question.

The links here.

and my code is right

// Setup

const myArr = [2, 3, 4, 5, 6];

// Only change code below this line

var total = 0

for (var i = 0; i < myArr.length; i++) {

total += myArr[i];

}

However, I am just confused as to how the code "total += myArr[i] can equate to 20 in the consolelog.

Can anyone kindly explain this?
console.log(total)

total starts out as 0
total = 0
Then the for loop runs from i = 0 to i = length of the array less 1
within the for loop the total is getting incremented each time by the value of the current number myArr[i]
So a table showing what happens may show
value of total
0
0 + 2
2 + 3
5 + 4
9 + 5
14 + 6
20

thank you so much that explains it perfectly.

the console log is also showing if i made i = 3. that the value console log would output 11. can you quickly explain that if you dont mind?

i really appreciate all your help.

Just starting my coding journey.

if i starts from 3 instead of 0 then
total is 0 again at the start
but we are adding
0 + myArr[3] and so we get 0 + 5
5 + 6
11

Can you try walking through what you think happens if i starts at 3?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.