Nesting For Loops different return from i & j question

I’m playing around with the code, and my question is why are the returns different when I log arr[i] and arr[j]. I solved the problem but I don’t understand the returns of i and j. Sorry for the silly question.

function multiplyAll(arr) {

  let product = 1;

  for ( let i = 0; i < arr.length; i++) { 
    for (let j = 0; j < arr[i].length; j++) { 
     // console.log(arr[i]);
    // console.log(arr[j]);

    }
  }

  return product;

}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
when I log console.log(arr[i]); it returns

[1, 2]
[1, 2]
 [3, 4] 
[3, 4] 
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]

And when I log console.log(arr[i]); it returns

[1, 2]
 [3, 4] 
[1, 2]
 [3, 4] 
[1, 2]
[5, 6, 7]

Using a simple letter for indexes in for loops is pretty common, but this is an example of how using meaningful variables names can help. What if instead, the code was:

for ( let subArray = 0; subArray < arr.length; subArray++) { 
    for (let subArrayIndex = 0; subArrayIndex < arr[subArray].length; subArrayIndex++) { 
      console.log(subArray);
     console.log(subArrayIndex);
    }
  }

If you read/run that, does it make it easier to keep straight?

The value in the brackets behind the array name is the index you target. If you check the values of i and j with console log, you will notice they are different. For every iteration of the outer loop, which uses i as iterator, the inner loop(j) will make one full cicle.
Maybe if you run this code it will make more sense:

for ( let outer = 0; outer < 5; outer++) { 
  for (let inner = 0; inner < 5; inner++) { 
    // this code will run 5 x 5 times
    console.log(`outer- ${outer}, inner- ${inner}`)
  }
  // this codes will run 5 times
  console.log('Outer loop did one iteration')
}

If you look closer, you will notice the outer loop will run once(make 5 iterations), while the inner loop will make full round for every iteration of the outer loop, i.e. it will make 5 full cicles.

1 Like

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