Iterate Through an Array with a For Loop 2019

Tell us what’s happening:
I am missing something but I cannot find it. I got two our of the four answers. I also do not understand why is i++ and not i+ if var myArr is only going up by one. Also why doesnt i = 2 if it starts from 2. I’m more concerned with the concept.

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
var ourTotal = 0;
for (var i = 0; i < myArr.length; i++) {
  ourTotal += myArr[i];
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 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

Hello,

change the name of your variable “ourTotal” to “total”, like it says in the exercise and it will work :wink:

1 Like

Hello @gobsiye,

You write i++ and not i+ because this is how it works, it’s standard. It’s equivalent to i = i + 1 or i += 1.*

In your code i start at 0, you initialize it in the for loop with var i = 0. So for every loop the for is doing i will increment by one.

I think you are confused with i and myArr[i] wich is different:

var i = 0 // this is a counter for the for loop
var myArr = [ 2, 3, 4, 5, 6] //  this is an array 
myArr[i] // will be equal to the value at the position i
myArr[0] = 2 // here i = 0 but the array at the position 0 is 2

I hope it will help you.