Use Caution When Reinitializing Variables Inside a Loop

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 = [0];
  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(row);
  }
  return newArray;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop

Please remember to actually ask a question so we don’t have to search for what the problem is.

This section is all about the power of console.log for debugging. Try running this code and open up the browser console (usually something like ctrl-shft-j) and see if those console.logs help you find the problem.

function zeroArray(m, n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  let newArray = [];
  let row = [0];
  for (let i = 0; i < m; i++) {
    // Adds the m-th row into newArray
    console.log('\n\nstarting row')
    for (let j = 0; j < n; j++) {
      // Pushes n zeroes into the current row to create the columns
      row.push(0);
    }
    console.log('ending row', row)
    // 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);
1 Like

Yes absolutely i’ll remember this. thanks !!

Hi @kevinSmith I’m unable to understand the problem and not able to solve this. can you please explain?

This is an exercise in debugging.

For this input:

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

We’re supposed to get this output:

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

This is the actual output:

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

You’re job is to use your logic and console.log statements to figure out what is going wrong.

Let us know if this is not clear or if you have a specific question.

2 Likes

This lesson’s instructions don’t really make sense to me. It says to reinitialize row after the n loop but that doesn’t work.

For instance, I tried adding row = 0; after ‘row.push(0);’ and after ‘newArray.push(row);’ and even after ’ return newArray;’, but none work. Where else would you reset to zero?

Also, how do you use the console.log on FCC? If you add a console.log statement and then hit ‘Run the Tests’, it’s either successful and moves you to the next lesson, or it isn’t successful but doesn’t execute the console statement you added.

Hi,

From the challenge instructions

Unfortunately, it’s not producing the expected output because the row variable isn’t being reinitialized (set back to an empty array) in the outer loop.

So you need to reset row back to initial state.
If you reassign value of row to 0 then you can’t push anything onto row.

let row = 0;
row.push(0); // that won't work

To see log to console use Developer Tool in your browser. Chrome and Firefox <ctrl><shift><i>

Thank you! That gave me enough of a hint to get it! :wink:

1 Like

Hi Kevin,

I know how to get [
[0, 0],
[0, 0],
[0, 0]
]

but I am wondering why actual output is [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
].

I think it would be [
[0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
].

Could you explain that please? Thank you!

5 Likes

I know how to get a output as wished,
but only by rewriting code and change input to (1,1)
:grinning:
what is the correct approach>>? really seems like the questions is getting overly complex to me
when there always is a simple solution…

Hi @donjon,
There is a mistake in that function. The challenge is for you to find the mistake in the function and fix it. You should really only have to change one line of code to fix the bug.

Calling zeroArray(3,2) should return [ [0,0], [0,0], [0,0] ]. Calling `zeroArray(1,1) is not fixing the function, that is changing the function parameters to 1,1

Let’s break it down
Given n=2, you make an array like [0,0] - an array of two zeroes - easy

var n = 2;  //second argument
var row = [];  // start with empty array
// push n zeroes onto array row
for( let j = 0; j < n; j++){
  row.push(0); // push 0
}
// [0,0]

OK - since m = 3 you need to do that three times to get [ [0,0], [0,0], [0,0] ]


var m = 3; //first arg
var n = 2;  //second arg
var newArray = [];  //start with empty array
for(let i = 0; i < m; i++){
  // code from above here
  newArray.push(row); // pack it with sub-arrays
}

return newArray;

Sounds simple enough. Should have zeroArray(3,2) returns [ [0,0], [0,0], [0,0] ]. But somehow the challenge code is different and doesn’t work as expected. What is different?

2 Likes

ye i know its allready a zero in row
thats why i changed one param to 1…
to onli add 1 zero in the row array and then created a new for loop with i=3
and add it 3 times in to newarray
but still i think its made overly complex for no gain solving it
if goal was to improve backend or something i understand but making pussles
on this level is ridiculus…

Not sure what you are trying to say here regarding backend.

The entire point of this challenge was to teach you how to debug existing code that had a small logic error. Using console.log statements, you could quickly see the following line should be moved from outside the outer for loop to just inside the outer for loop to get the desired result.

let row = [];
5 Likes

And as someone that is constantly helping people who lack basic debugging skills, I wish there were more of these kinds of exercises.

6 Likes

Hello all,
I Have the same question as @awesomeHu had above 9d ago and i didn’t see an answer to that in the timeline. Could someone explain this or maybe direct me to some documentation that will explain the concept.
cheers,
Justin

Hello!
I had the same question as @awesomeHu, @Juskink

And that’s what i found
Problem is that row never resets. Arrays and objects act as pointers in JavaScript. When you push row into the matrix array, you are pushing a pointer to row into the matrix array, not a copy of row at that point in time. The next time you change row by pushing a 0 onto it, the row already in the matrix array changes too. That’s because matrix[0] is a pointer to a location in memory, and when you call row.push(0), you are changing that location in memory. Therefore the next time you call matrix[0] it will include all changes you’ve made.

You’ll find that matrix[0] === matrix[1]. Same is true for matrix[2]. They are all three pointers to the same location in memory (row).

To solve this, you want to put your row = [] inside the first for loop. This tells it to make a new row (or a new location in memory) every iteration.

If you want to get your expected outcome of 2 columns, 4 columns, 6 columns, then instead of pushing row to matrix, push row.slice(0). This pushes a copy of row to matrix, meaning that all subsequent changes to row will not affect the copy that you pushed. That is, matrix will not contain a pointer to row, but a pointer to a copy of row at some point in time.

Hope this helps. :wink:

13 Likes

Hi awesome guys, I will you my solution
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(row);
row = [];

}
return newArray;
}

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

11 Likes

function zeroArray(m, n) {

let newArray = [];
let row = [];

//console.log(“Before for”);

for (let i = 0; i < m; i++) {

//console.log("row working");

for (let j = 0; j <n-1; j++) {
  
//  console.log("coloumn working");
  
row.push([0,0]);

}

}
return row;
}

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

Here’s my working 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 = 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(row);
  }
  return newArray;
}

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