Help me understand "Iterate Through an Array with a For Loop"

Hello guys, im on the Iterate Through an Array with a For Loop challenge and im finding difficult to understand the logic behind it.
so, i checked the results and the correct code would be:

// Setup
var myArr = [ 2, 3, 4, 5, 6];
var total=0
for (var i =0; i<myArr.length; i++){
total+=myArr[i]
}
console.log(i)

and this was on the code explanation:

total + myArr[0] → 0 + 2 = 2

total + myArr[1] → 2 + 3 = 5

total + myArr[2] → 5 + 4 = 9

total + myArr[3] → 9 + 5 = 14

total + myArr[4] → 14 + 6 = 20

Let me put into words what i think is going on here:
We have an array with 5 numbers and a variable total=0
Initializing the loop we declare that var i equals 0 and that the code will run as long as i is less than 5 and if that’s true, we will add 1 to i.

Until here total still equals 0, but how does myArr[i] equals 2??? i thought 2 was the n°0 on the array so wouldn’t myArr equal 3 since it was 1 was added on the last part of the loop?

You have the steps of loop execution out of order

for (initialization; loop condition; increment) {
Loop Body
}
1. Loop initialization - in your case, i is created and set to 0

2. Loop condition check - in your case, the code checks if i < myArr.length

3. Loop body executes - in your case, myArr[i] is added to the total

4. Loop increment code - in your case, i is increased by 1

5. Go back to step 2

1 Like

gosh, i dont know why i’m finding it so hard

so here it jumps to the total+=myArr[i] part?

I don’t know that I would use the word ‘jumps’, but yes, a for loop always executes those steps in that order.

1 Like

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