Iterate Through an Array with a For Loop Not totaling to 20

I get an error message the total must be 20.

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

{

console.log( myArr[total]);

}


// 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



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


{

console.log( myArr[total]);

}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop

So I think some of the confusion may be the use of ‘total’ as the loop counter here. In a for loop we often declare an initial counter variable (i commonly), a way to exit the loop, and something to do at the end of each iteration (like increment the counter). In the example: Variable i is the counter and begins at 0. Exit IF i is not less than the array length. After each iteration of the loop, increment i by 1.
All this is doing is creating a way for us to step through each item of the array ourArray and do something with it. These kinds of for loops could be read as: “For each item in Array, do something…”, in this example it reads: "For each item in ourArray add that item to the variable ourTotal"

You want a variable myTotal that is equal to 2 + 3 + 4 + 5 + 6, all the items in myArr

1 Like

Thanks this was helpful. I was able to complete the exercise!!