Very confused with Iterate Through an Array with a For Loop

First, I perfectly understand what’s happening with this piece of code here:

var myArray = ;

// Only change code below this line.
for (var i = 1; i <= 5; i++) {
myArray.push(i);
}

It’s adding 1 (i++) to the numbers below 5 and it stops when 5 is reached, so we have 1, 2, 3, 4, 5.

But I can’t understand the following code:

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];
}

What is driving me crazy is the fact I can’t see how it could be useful in a real project, for what reason I’d use this, and why we’re using i++ in this case. I passed the test but I need to understand what’s going on.

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/iterate-through-an-array-with-a-for-loop

1 Like

Iterating through arrays is SUPER useful, but admittedly seeing abstract tiny examples doesn’t really show you why they are so cool.

Let’s use some of the later projects as examples…

Let’s say you are gathering a bunch of Wikipedia entries and want to dynamically render them to the screen - you might do that by setting up a little template that pulls all the data from objects you have stored in an array. Then all you do is iterate through the array and pump out the values for your template. You can use a similar trick with the Twitch project, too.

Let’s say you want to make a game where the players moves have to be checked against a winning condition, like tic-tac-toe or Simon. Again, storing these in arrays and iterating through those arrays is useful.

Aside from the projects, lots of the algorithms can be solved with iterating through arrays, too.

Once you start real algorithms and projects, the uses for iterating through arrays should become clearer.

2 Likes

Thank you, it helped me.