Tell us what’s happening:
Hey all! New to JavaScript, I’ve got the solution for this, but I don’t understand what’s actually happening in the loop. I’m going to try my best to explain what I think is happening, and I hope that someone can figure out where my logic went wrong.
From my understanding,
i represents the placement inside the array, which starts at a 0-count.
so the outside for loop will continue until i === 3 (the length of the outside array)
during this, j represents the placement inside of the nested array
which will stop the second for loop when j === (the length of the array (in the position of i??? I think this number is 3? but I don’t quite understand that)
then somehow the product (which I know I can write it product *= arr[i][j]) is multiplied by the array outside and inside??
what I don’t understand is if i has a value that is determined inside the loop, how is it also equivalent to the value that is in that position?
and if this code were to stay, wouldn’t j be limited to the number of elements inside the first array?
for example, the array [[1, 2, 3, 4], [5, 6], [7, 8]] wouldn’t work because the length of arr[1] would be 3, but there are 4 values inside the first nested array?
Can someone break down what is actually happening in each loop for me? I’m struggling to comprehend this, and I feel like I’m going to have trouble with concepts further on if I don’t have this foundational understanding.
Thank you so much for your time and your energy in advanced!
The Solution
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]
console.log(product)
}
}
// 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 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/113.0
Challenge: Basic JavaScript - Nesting For Loops
Link to the challenge: