Debugging exercise, loops

IN REGARDS TO EXCERCISE: Debugging: Use Caution When Reinitializing Variables Inside a Loop

I had no problem fixing the bug here by reinitializing the “row” variable, but there is something that is really bothering me about this exercise. Why does the original code with the error in it create an array of 3 arrays, each with 6 zeros? I know I am missing something and it is really irritating me, I know this is probably very basic but any help in the matter would be greatly appreciated.

Thanks,

It’s tedious to find exercises by name: could you include a link to the challenge?

Ok I think I understand by going through this several times on my own in the console, however any confirmation would be of great help. My error was assuming that in each iteration of the loop the thing being pushed was the values in the array being pushed e.g. “row” which was equal to [0,0], then [0,0,0,0], then [0,0,0,0,0,0] which is why I was initially confused, I thought that the array “newArray” should be [[0,0],[0,0,0,0],[0,0,0,0,0,0]]. However, it was showing three arrays of 6 zeros each. After much testing, it seems to me that what is pushed to the array in the loop is the variable “row” itself and not its current value, which means that the “newArray” variable was actually [row, row, row], and only became numbers at the end of the loop, which means that all array index items were the same, the last value of “row” which was [0,0,0,0,0,0]. Thanks to anyone who read along with my frustrating fun for the day, please let me know if I’m correct on this.
thanks again,

you are correct that the returned value is `[row, row, row]`, but you don’t see 18 zeroes because it is converted to numbers later, but because there are three references to the same array

you can see it visualized if you look at the code with this tool. http://pythontutor.com/javascript.html#mode=display

like this:

1 Like

Ahhh I see as you change the “row” variable you’re also changing the index items of newArray as you go, thanks so much, I’m saving this tool