Confused! Iterate Through an Array with a For Loop

in order to pass this task my code needs to:

1. `total` should be declared and initialized to 0

2. `total` should equal 20

3. You should use a `for` loop to iterate through `myArr`

4. Do not set `total` to 20 directly

QUESTION: My code below is the solution to the problem. In other words I passed, however, I still don’t understand how ‘total’ is equal to 20.

``````
// 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];

// Only change code below this line

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

``````

You code just iterates through the array elements and adds the value to the existing value of total. If you add the following console.log statements, you can see what is happening using your browser’s console (Ctrl+Shft+J in Chrome):

``````var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length; i++){
console.log('i = ' + i + ', myArr[' + i + '] = ' + myArr[i] );
console.log('add ' + myArr[i] + ' to the current value of total (' + total + ')');
total += myArr[i];
console.log('total is now equal to ' + total);
}
``````

The above will show the following in the console:

``````i = 0, myArr[0] = 2
add 2 to the current value of total (0)
total is now equal to 2
i = 1, myArr[1] = 3
add 3 to the current value of total (2)
total is now equal to 5
i = 2, myArr[2] = 4
add 4 to the current value of total (5)
total is now equal to 9
i = 3, myArr[3] = 5
add 5 to the current value of total (9)
total is now equal to 14
i = 4, myArr[4] = 6
add 6 to the current value of total (14)
total is now equal to 20
``````
1 Like

Wow thank you for the explanation. Thanks for the value you add here!!