# freeCodeCamp Challenge Guide: Iterate Through an Array with a For Loop

freeCodeCamp Challenge Guide: Iterate Through an Array with a For Loop
0

#1

A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:

``````    var arr = [10,9,8,7,6];
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
``````

Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our `condition` for this loop is `i < arr.length`, which stops when i is at length 5.

#2

Hi Rafase, first I want to thank your posts, are very useful for me. Now im still working the front end cert, and I take a break to study with books and manuals more in deep some structures, I found the for-in loop and it seems that is better method to iterate through arrays and objects. What do you think about it?

#3

for of or fo in depending your version of ES is what I use for objects now a days.

#4

A bit late to the game but itâ€™s better to take `arr.length` out of the loop so for better performance (not so much in JS since itâ€™s a property but as a general rule)

``````    var arr = [10,9,8,7,6];
for (var i=0, l=arr.length; i<l; i++) {
console.log(arr[i]);
}
``````

or as an alternative

``````arr.forEach(function(item) {
console.log(item);
});
``````

#5

Hey my friends i am pretty new to js and while fallowing the exercises im having trouble deciphering the logic. can yall help me understand why this code i have written is not correct?
// 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];
var myTotal =0;
// Only change code below this line
for(var i = 0;i<= myArr.length; i++) {
myTotal+=myArr[i];
}

#6

Hi, you need to declare and initialise the variable first. You also do not need the equals sign in your for loop. Iâ€™m new here so canâ€™t help much more but I hope that does it for youâ€¦

#7

You also need to change â€śmyTotalâ€ť to â€śtotalâ€ť

#8

wow ok thank you ive been stuck for about an he hahaha

#9

Iâ€™m having a hard time understanding the math behind this one. I understand each component, just not how you use it all to get to total=20. Would someone mind helping me out?

#10

I was given a pretty good explanation on Gitter. My missing link had to do with

`myTotal += myArr[i];`

I was missing that it with every iteration it adds `i` to the last iterations sum. So: 2 + 3 + 4 + 5 + 6 = 20.

Oops!

#11

Yeah, itâ€™s confusing. I thought that the instructions say total should equal 20 and I had it in my head that that sum of all the contents in the total array needs to equal 20.

You can run all of your code in eloquentjavascript.net and finish it off with a console.log() to see what your code is pushing out. Sometimes itâ€™s not you. Itâ€™s the instructions.

#12

Awesome!!! Thank you so much for that!

#14

Hi, I have the same question as you did. But I still donâ€™t understand it very well.
Would you please share with me about how it runs and ended up adding each element together and become 20?

What I dont understand is â€śi+=1â€ť, doesnâ€™t it add â€ś1 " to each element each time? (Ex: 2+1 =3 ; 3+1=4)
and theâ€ť i = 0", does it mean that it will start to count from the number 2 of [2,3,4,5,6] ?
// Setup
var myArr = [ 2, 3, 4, 5, 6];

// Only change code below this line
var total=0;
for (i=0 ; i<myArr.length; i+=1){
total += (myArr[i]);
}

#15

Hello. If you follow the pseudo code for the for loop, the question youâ€™re posing can then be easily answered. The part thatâ€™s i+=1 or simply written as i++ is the action the loop will take after running the code within the parentheses.
For example,
for (i = 0; i < myArr.length; i++) {
total += myArr[i];
}
In this code, the i++ part increments the iterations from 0 to the length of the array myArr while performing the summation.

#16

`var myArr = [2, 3, 4, 5, 6];`
`for (var i = 0; i < myArr.length; i++)`

So since the code uses base 0 counting, `i=0` tells the code to start with the first place in the array, which in this example is `[2]`. `i=1` would be place number two or `[3]`. `i=2` would be place number three or `[4]`. Rinse and repeat until youâ€™ve reached `i=4` which is the last place. Since `myArr.length` counted five places in the array, and youâ€™re at `i=4` (place number 5), the middle part of the for loop `i < myLength;` tells the code to stop before it gets to `i=5` (or place number 6).

To find the our answer output or `total=20` you need to look at the portion that comes after the for loop setup: `total += myArr[i];`.

This tells the code that in each loop, youâ€™ll need to add which ever spot in the array youâ€™re at to the already established `total`. So with loop number one, you have `0` (remember, `total` was set equal to `0` at the beginning) being added to `2` because youâ€™re using the item in the first spot in the array. This gives you `total = 2`. You have now stored the number two in the `total` variable.

After the code has calculated the `total` for this loop, it refers back to the `i++` and then adds `1` to `i`. (Remember, youâ€™re using Base 0 counting, so the `[2]` is actually at place number 0, etc.) If weâ€™re starting at the beginning, this adds `1` to `i=0` giving you `i=1` and the begins the next loop with `for (var i=1; i <= myArr.length; i++)`. (This is only used when working through the loop so that the code knows where itâ€™s at in the array and when to stop running.)

Now it repeats the same process for each part of the array, adding along the way.

Loop 0: Find the item in the first place: 2.
Count the number of places in the array: 5.
Add the item from the first place to the stored `total=2`: 0 + 2.
Return to `for loop` instructions and complete `i++`. `i=0` and `i++` means to add `1` to `i`, so you now have `i=1`. On to the next loop.

Loop 1: Find the item in the second place: 3. (because we now have `i=1` from the previous loop)
Count the number of places in the array: 5.
Add the item from the second place to the stored `total=2` from loop 0: 2 + 3 = 5.
Return to `for loop` instructions and complete `i++`. `i=1` and `i++` means to add `1` to `i`, so you now have `i=2`. On to the next loop.

Loop 2: Find the item in the third place: 4. (because we now have `i=2` from the previous loop)
Count the number of places in the array: 5.
Add the item from the third place to the stored `total=5` from loop 1: 5 +4 = 9.
Return to `for loop` instructions and complete `i++`. `i=1` and `i++` means to add `1` to `i`, so you now have `i=3`. On to the next loop.

Loop 3: Find the item in the fourth place: 5. (because we now have `i=3` from the previous loop)
Count the number of places in the array: 5.
Add the item from the fourth place to the stored `total=9` from loop 2: 5 + 9.
Return to `for loop` instructions and complete `i++`. `i=1` and `i++` means to add `1` to `i`, so you now have `i=4`. On to the next loop.

Loop 4: Find the item in the fifth place: 6. (because we now have `i=4` from the previous loop)
Count the number of places in the array: 5.
Add the item from the fifth place to the stored `total=14` from loop 3: 6 + 14 = 20.
Return to `for loop` instructions and complete `i++`. `i=1` and `i++` means to add `1` to `i`, so you now have `i=5`. Now because `i<myArr.length` tells the code to only run when `i` is less than the length of the array and no larger, it stops. If we were to continue, `i` would equal five and that would make the statement no longer `true`. So itâ€™s gotta stop.

Finally, we return `total = 20`.

1: I REALLY hope this is all correct. Itâ€™s only my understanding of it all plus some research, but Math and I donâ€™t always get along.

2: Iâ€™m sorry that itâ€™s so long, but I wanted to make it was thorough and accessible.

If you still have a hard time understanding it, lemme know and Iâ€™ll see if I can do it some other way!!

#17

WOW~ Thank you soooo much for the detail explanation!
It helps a lot and finally this made sense to me now.
I really appreciate it!!

#18

#19

What a well thought out and amazing description.

Thanks!

#20

Hi all , if anybody still need a working example hereâ€™s one

var myArr = [ 2, 3, 4, 5, 6];
var total = 0;

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

for future reference always check for typeof [mistyping]
mistyping is most common issue for me.

#21

Perfect explanation, thank you so much!