Iterate Through an Array with a For Loop challenge help

Forgive me if I’m in the wrong place with this question, I tried to post to the thread pertaining to this challenge but absolutely could not find a way to add a reply. freeCodeCamp Challenge Guide: Iterate Through an Array with a For Loop

the challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop

For this challenge I am skeptical of how I arrived to my solution, though I did technically pass. All the other solutions offered in the hint thread differ from mine, making me fear I am missing something.

my solution:
var total = 0;
for (total; total < 20; total += myArr[0]) { }

Is this logical ?

Thanks!
Tim

That is a bad way to use a for loop. Don’t do this.

First, you shouldn’t do work in the head of the loop except in some particularly rare cases that don’t really happen in Javascript.

Second, you hard coded the answer of 20 instead of actually adding all of the array elements together.

1 Like

Hi Jeremy thanks for the reply,

Can you clarify what “work in the head of the loop” means so I don’t repeat that mistake?

Also, I’m unsure how I hard coded the answer of 20; I’ve declared my variable with value = 0. My condition within my loop simply stops iterations if total is less than 20. If I modify the value of expression b or expression c within my loop, I fail the challenge.

Can you unpack either of those a bit further for me please?

Thank you!
Tim

The for loop ‘head’ should do exactly three things

  1. initialize an iteration variable
  2. set an exit condition based upon the iteration variable
  3. set how the iteration variable gets update

The solution for this challenge should say ‘start at the first array entry, continue through all array entries, incrementing one by one’ with a body that says ‘add the current array element to total’.

Your loop says ‘keep adding the first element to the total until we reach 20, the value I knew ahead of time was the answer’.

If you change the order of the contents in arr, would you get the same answer? Hint: you won’t. This is a big problem.

1 Like

Not really sure how you came up with that solution based on what is taught in the curriculum?


This challenge can be passed with the wrong code in various ways. It does not check that the array elements are added to total.

var total = 0;
for (var i = 0; i <= 20; i++) {
  myArr[0];
  total = i;
}
var total = 0;
for (var i = 0; i <= myArr[3] * 4; i++) {
 total = i;
}

The requirements should probably be stricter and expect either

total += myArr[i]

or

total = total + myArr[i]

to be inside the body of the for loop.


I created an issue for it.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.