 # Use Caution When Reinitializing Variables Inside a Loop Still getting wrong answer why?

Use Caution When Reinitializing Variables Inside a Loop Still getting wrong answer why?
0

#1

Tell us what’s happening:

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(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(0);
}
return newArray;
}

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

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36`.

Blockquote

#2

This is answer why?

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

``````// 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);

#3

You need your first ‘for loop’ to push 0’s into the row array ‘n’ number of times, when that ‘for loop’ is done, you need a second for loop to push the new row array into the newArray array ‘m’ number of times. If you put the for loops inside one another, the first ‘for loop’ will push 0 into the row array just one time then move to the second ‘for loop’ and push the array ‘m’ number of times into new array. Then it will go back to the first ‘for loop’ and repeat.

``````function zeroArray(m, n) {
let newArray = [];
let row = [];
for (let i = 0; i < n; i++) {
row.push(0);
}
for(let j = 0; j < m; j++){
newArray.push(row);
}
return newArray;
}

zeroArray(3, 2); //output: [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
zeroArray(4, 2); //output: [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]

``````

#4

Awesome explain. I got it now

#5

Why don´t we get an array like this instead, before editing the code?

[[0,0],[0,0,0,0,],[0,0,0,0,0,0]]