Iterate Through an Array with a For Loop Getting Total to 20

Tell us what’s happening:
For some reason, I can’t get the total to equal 20.

Your code so far

// 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 i = 0; i < myArr.length; i++) {
   var total = 0;
   total += myArr[i];

Your browser information:

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

Link to the challenge:

1 Like

You reset total to zero every time the loop runs, so it will always return the last value in myArr.

1 Like

So what you’re doing is, inside your loop, setting total to zero. And then adding the next number to zero. Do you think that’s ever going to reach twenty?

Where should total be initialized and set to zero instead? (hint: take a look at the example provided, where does ourTotal get set to zero?)

And dang it, @ArielLeslie, your fingers are just too fast. :wink:

Thank you, I understand now.

1 Like