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

Iterate Through an Array with a For Loop


Hints

Hint 1

Remember the structure of a for loop:
for ([initialization]; [condition]; [final-expression]) statement

  • The [initialization] part is executed only once (the first time).
  • The [condition] is checked on every iteration.
  • The [final-expression] is executed along the statement if [condition] resolves to true.

Hint 2

Remember how accumulators work:
let x += i

  • The variable x is going to act as the accumulator.
  • The variable i is the one which value will be stored (and accumulated) inside x
  • The expression += is an just abbreviation of x = x + i

Solutions

Solution 1 (Click to Show/Hide)
let total = 0;
for (let i = 0; i < myArr.length; i++) {
  total += myArr[i];
}

Code Explanation

  • Initialization: i gets a value of 0 and its used as a counter.
  • Condition: the subsequent code is executed as long as i is lower than the length of myArr (which is 5; five numbers but arrays are zero based).
  • Final-expression: i is incremented by 1.
  • Statement: The function adds myArr[i]'s value to total until the condition isn’t met like so:
total + myArr[0] -> 0 + 2 = 2 
total + myArr[1] -> 2 + 3 = 5
total + myArr[2] -> 5 + 4 = 9
total + myArr[3] -> 9 + 5 = 14 
total + myArr[4] -> 14 + 6 = 20
Solution 2 (Click to Show/Hide)
let total = 0;
for (let i = myArr.length - 1; i >= 0; i--) {
  total += myArr[i];
}

Code Explanation

This works similarly to the last solution.

  • Initialization: i is initialized with the value myArr.length - 1.
  • Condition: the loop is executed as long as i is greater than or equal to 0.
  • Final-expression: i is decremented by 1.
  • Statement: The function adds myArr[i]'s value to total until the condition isn’t met:
total + myArr[4] -> 0 + 6 = 6
total + myArr[3] -> 6 + 5 = 11
total + myArr[2] -> 11 + 4 = 15
total + myArr[1] -> 15 + 3 = 18
total + myArr[0] -> 18 + 2 = 20

Relevant Links

61 Likes

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?

8 Likes

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

1 Like

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 Likes

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 Likes

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…

3 Likes

You also need to change “myTotal” to “total” :slight_smile:

7 Likes

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

2 Likes

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?

8 Likes

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! :stuck_out_tongue:

13 Likes

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. :slight_smile:

16 Likes

Awesome!!! Thank you so much for that!

1 Like

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

6 Likes

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.

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

143 Likes

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

2 Likes

Thank you for your help!~

What a well thought out and amazing description.

Thanks!

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.

10 Likes

Perfect explanation, thank you so much!