# ***https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop

What may I do to have two columns??

you are asking an impossible question

• what are you talking about?
• what have you tried so far?
• what’s going wrong?
• what have you tried to fix that?
1 Like

What have you tried? What problems have you run into? What is behaving differently than expected?

1 Like

what have you tried so far? I tried the change of the values of (let matrix zeroArray(3, 2)) and I ignored de inner loop by using //. I could not try console.log() because I do not know how to use it in this case.

what’s your current code? This is my current code.

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

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

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

what’s going wrong? I think is my inner loop. I changed the conditions of it, but I did not get any positive result.

what should happen instead? I am getting zeroes in function of the rows. I should get rows in function of the values of (let matrix = zeroArray(3, 2);). I should get : [ 0,0] , [0,0 ], [0,0 ],].

what have you tried to fix that? I tried to change the values of the conditions of inner loop and the outer loop. I got the three rows, but I did have the two columns yet.

What is behaving differently than expected?
I want to get this.

I am getting colums in function of the rows. If I set 4 rows, I get 4 columns.
What have you tried? I changed the values of the conditions of inner loop and the outer loop. I got the the three rows, but I did not get the 2 columns.

stuff is at the same time a bit more complex than that, and also a bit more simple in terms of fix

the issue is as said in the title, the declaration of the variable
arrays work by reference

``````let arr = [0,0,0]
let b = a
b = 1;
console.log(a) // [0, 1, 0]
``````

something similar is going on in your code

newArray ends holding three different references to the `row` array - `row` is not copied in the `newArray` by the push method, the push method adds a reference to the `row` array in the `newArray` array

you can think of the `newArray` as being `[row, row, row]`

the fix is pretty simple in terms of changes to the code
but conceptually it involves variable scope, and a bit of reflection