Help for ExplanationBasic JavaScript - Nesting For Loops

Tell us what’s happening:
Hello Guys,

I’ve solved this exercise cause I was following the instruction given. but i don’t quite understand on the code im writing. could someone please help me to explain me the code please?

I’m wondering why we need another loop after the loop. and on the nested loop why do we use arr[i].length?

  **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++) {
    product = product * arr[i][j];
  }
}
// Only change code above this line
return product;
}

console.log(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/105.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Nesting For Loops

Link to the challenge:

To answer the question about why two for loops are needed, you need to look at what the input of this function is.

Please try to describe this input, in your own words…

hey there, thanks for responding, my understanding is that one for the first array and the second is the array within the array. not sure if im correct.

The input is an array of arrays (otherwise called a two dimensional array).

So if you imagine a 2-D table. It has rows and columns. To iterate over it, you need to go row by row, but also column by column.
And that’s why you need two for loops (one nested inside the other)

Got it thanks, and how about arr[i].length? what is it and why we use it for the other loop instead of arr.length?

You are dealing with array inside array situation here.

So arr is array, and it has bucnh of arrays inside. Let’s call them subarrays.

Thus arr[i] - it is one of subarrays

So, it has length just like all other arrays and we can use it depending on our purposes.

so arr[i] is subarray while arr is the outter array?

About terminology I am not sure, my english is little off.

run the below code somewhere, and look into console:

const twoDArray = [
  [1, 2, 3],
  [4, 5],
  [6, 7, 8, 9]
  ]
  
for (let i = 0; i < twoDArray.length; i++) {
  console.log(`the below is subarray with index ${i}`)
  console.log(twoDArray[i]);
  console.log(`it has length: ${twoDArray[i].length}`);
  console.log('---');
  for (let j = 0; j < twoDArray[i].length; j++) {
    console.log(`the below is element with index ${j} of subarray mentioned above`);
    console.log(twoDArray[i][j]);
    console.log('---');
  }
  console.log('----------------');
}
1 Like

wonderful! thanks a lot! this explain much clearer.