Nesting for loops question

Tell us what’s happening:
So I completed the challenge but I wanted to clarify something.
why console.log[i] logs this:

12345891012131415116716
function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i]);

  }

}

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

I know it has something to do with J , my assumption it prints (1,2) twice, because that’s the only option, and so with 3,4 and three times 5,6,7 because it has it three times.
But… I was only checking arr[i] I have it in my head I just need someone to clarify it better for me ty! :slight_smile:
I know if I type console.log(arr[i]) before i declare J, it will only log once.
(Or is it because arr[i] I’m trying to access that array, and it logs all the possible variants.)
Your code so far


function multiplyAll(arr) {
let product = 1;
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i]);

}

}

// Only change code above this line
return product;
}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
  **Your browser information:**

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

Challenge: Nesting For Loops

Link to the challenge:

The outer for loop goes through each element in arr, which are also arrays (I’ll refer to them as subarrays), and the inner for loop goes through each element in the subarray. So if the first element in arr is a subarray of two elements then the inner for loop will run twice, once for each element in the subarray.

To use real numbers here, if the first element in arr (arr[0]) is [1,2] then when i is 0 for the outer for loop, the inner for loop will run twice because there are two elements in the subarray. Hence, console.log(arr[0]) will be executed twice and [1,2] will be logged twice.

Yeah that’s what I thought, thanks for clarifying.

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