# Iterate Through an Array with a For Loop - Just need help understanding

Iterate Through an Array with a For Loop - Just need help understanding
0

#1

So I was able to complete the challenge with this code:

``````// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}

// Setup
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;

for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}

``````

Now my question is, how does this formula know to stop and get ‘total = 20’? Does the formula cap out at the sum of all of the integers in the array?

#2

The variable i in the for loop represents an index of myArr. During each iteration, myArr[i] represents a different element in myArr. The variable total starts off as 0 and during each iteration, an element (a number) in myArr gets added to total. The iteration stops when the express i < myArr.length is no longer true. Siince myArr.length is 4 in this example and i starts at 0, once i becomes 4 (due to the i++ incrementing at the end of each iteration), the loop stops and total has the value 20.

#3

Oh okay, I understand now. Once again Randell, thanks so much!

#4

I may have misunderstood everything but I think that in this example, myArr.length is 5 and myArr has an index of 4.
// Setup
var myArr = [ 2, 3, 4, 5, 6];

#5

Most likely a slip up… in the //Example `myArr.length` does have a length of 4, while in //Setup it’s a length of 5.

So yeah, for //Setup, `i < myArr.length` stops being true and breaks out of the loop once `i` reaches a value of 5, meaning it only does 4 iterations and the total is 20.

#6

Thanks! Just needed to check in case I was missing smt.