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?
could someone please help me out on this? what am i getting wrong?