Help needed with Test You Skills: Arrays 3

Hello!

I have browsed other peoples posts and was able to use the ForEach() method to iterate through the array, I was just curious why this didn’t work? I also was able to make a for loop work properly, but not a for ... of.

Also this is my first post so please let me know if my formatting or approach to my question could improve.
Thank you!!

Here is the codepen:

Hi @DanielMuller and welcome to the community :wave:

The problem is that you can’t change an array item directly by change the loop variable item. To remind us of that it’s best to always use for (const item of myArray).

You have several possibilities:

  • Using a traditional for loop like you did in your other version.
  • Using forEach() which has a form that includes the index and then assign the new value to myArray[index].
  • Using a for...of loop that iterates over the entries() of the array. Every entry is an array that contains the index and the item.

I hope that helps. Feel free to ask questions. :slightly_smiling_face:

See you,
Michael

Very cool. Thank you for the explanation!! :grin:

1 Like