Debugging - Use Caution When Reinitializing Variables Inside a Loop

Tell us what’s happening:
Describe your issue in detail here.

I can’t understand why newArray[0] keeps changing it’s value. I thought that when you push an element into an array the previous values remain the same. Example:
let array = [0,1,2]
array.push(3);
console.log(array) → the output here is [0,1,2,3] and if we access array[0] we can see the value of it will be 0 ( array[0] == 0 in our case). I have tried the same test with arrays and strings and it does not seem to matter the previous values remain the same. Therefore why do the previous values of newArray (newArray[0], newArray[1] and so on) keep on changing after we apply the push method
Your code so far

function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
  // Adds the m-th row into newArray

  for (let j = 0; j < n; j++) {
    // Pushes n zeroes into the current row to create the columns
    row.push(j);
  }
  // Pushes the current row, which now has n zeroes in it, to the array

  newArray.push(row);
  console.log(newArray[0]);
}
return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0

Challenge: Debugging - Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

try with

let array = [0, 1, 2];
array.push(3);

const newArr = [];
array.push(newArr);

newArr[0] = 1;
array.push(newArr);

newArr.push(3);
array.push(newArr);

what’s the value of array at the end?

try to run the code with this tool for a visual rapresentation of what happens: Online JavaScript Compiler, Visual Debugger, and AI Tutor - Learn JavaScript programming by visualizing code

I’ve tested the code you’ve sent and I know that the value of array is :
[ 0, 1, 2, 3, [ 1, 3 ], [ 1, 3 ], [ 1, 3 ] ].
However when I’ve tried to solve the problem with pen and paper, my own logic told me the value of array should be: [0,1,2,3,[ ],[1],[1,3]]. Can you please explain ?

Look at the visual rappresentation With the tool I posted above, try following what happens there

1 Like

I checked the code with the tool you sent me and, to me, it seems as if the the indexes array[4],array[5],array[6] have a reference with newArr so whenever you push newArr to array the code not only creates a new slot for that specific push but it also changes the previously pushed slots to match the newArr you have just inserted. I don’t know if I made my self clear or not but that is how I see it and I hope it’s correct. If you can confirm my analysis that would be great . Thank you for the help! :smile:

Yes, those indexes reference the same array

1 Like

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