Understating the Nesting For Loops

I am trying to break (the code given in example down) to understand but It is confusing me, below is my code and comments to see what I think it is in each loop. Then why result is different?


fvar arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) { // 0,1,2
  for (var j=0; j < arr[i].length; j++) {
    //arr[i] = [1,2]; j = 0
    //arr[i] = [3,4]; j = 1
    //arr[i] = [5,6]; j = 2
    console.log("arr with ij is " +arr[i][j]); 
                //[1,2][0]
                //[3,4][1]
                //[5,6][2]
  }
}

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops

More like this

for (var i=0; i < arr.length; i++) { // 0,1,2
  for (var j=0; j < arr[i].length; j++) {
    /** For i = 0  **/
    //arr[i] = [1,2]; j = 0
    //arr[i] = [1,2]; j = 1
    console.log("arr with ij is " +arr[i][j]); 
                //[1,2][0]
                //[1,2][1]

     /** For i = 1  **/
    //arr[i] = [3,4]; j = 0
    //arr[i] = [3,4]; j = 1
    console.log("arr with ij is " +arr[i][j]); 
                //[3,4][0]
                //[3,4][1]

     /** For i = 2  **/
    //arr[i] = [5,6]; j = 0
    //arr[i] = [5,6]; j = 1
    console.log("arr with ij is " +arr[i][j]); 
                //[5,6][0]
                //[5,6][1]
  }
}

Basically, Your arr[i] does not change until j has completed its loop entirely

1 Like

and I am lost. I don’t understand what is happening.

Do you understand how a single for loop works without nesting?

yes, I do. what is confusing to me when you wrote in comments

    /** For i = 0  **/
    //arr[i] = [1,2]; j = 0
    //arr[i] = [1,2]; j = 1

why loop is going over arr[i] twice in each loop?

Because j has to finish before it goes to the next i iteration

I am lost, sorry but can you expand on your answer?

Ok, if you forget about nesting for a second and ran just 1 single loop , this would your outcome

for (var i=0; i < arr.length; i++) { // 0,1,2
  // arr[0] = [1,2] // Inner loop would iterate through this first
  // arr[1] = [3,4] // Inner loop then iterates through this
  // arr[2] = [5,6] // Inner loop will finally iterates through this
}

so when you include your inner loop it iterates through each content of the upper loop and
if you look at it separately, your inner loop will first

for (var j=0; i < arr[0].length; j++) {
  // arr[0][0] = 1
  // arr[0][1] = 2
}

then after it finishes the above it goes to the next arr[i] which is arr[1]

for (var j=0; i < arr[1].length; j++) {
  // arr[1][0] = 3
  // arr[1][1] = 4
}

Finally it goes to the last arr[i], which is arr[2]

for (var j=0; i < arr[2].length; j++) {
  // arr[2][0] = 5
  // arr[2][1] = 6
}