# Trying to understand nested loops

Hi all, I’m currently making my way through the javascript training and I’m on the ’ Basic JavaScript: Nesting For Loops’ lesson. I have the code below and understand why it’s doing what it’s doing.

``````function multiplyAll(arr) {
var product = 1;
for(var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = product * arr[i][j];
}
}
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
``````

However, I’m trying to get my head around how the computer works through it as this usually helps me get my head round it better. Am i right in that it works in the following way.

Note: The console logs below are mainly for my own testing area that I have to make notes

//first loop runs
[i] //var ‘i’ setup
[0] //var ‘i’ given value of 0
//second loop runs
[0][j] //var ‘j’ setup
[0][0] //var ‘j’ given value of 0
console.log(arr[i][j]);//this shows the number within arr[i][j] which is currently at arr[0][0], thus it shows ‘1’
[0][1]//the sub loop runs through again and adds +1 to j, which becomes 1
console.log(arr[i][j]);//this shows the value of [0][1], which is ‘2’

/*the sub ‘for’ loop is now complete as arr[1].length matches the length of the sub array,
we then return to the first for loop, which is still initialised at [0] */

[1][j]//+1 is added to the first for loop
[1][0]//j is initialised to 0 again within the sub ‘for’ loop. This is because it completed its function last time after meeting the arr[1].length
console.log(arr[i][j]);//this shows the value of [1][0], which is ‘3’
[1][1]//the sub loop runs through again and adds +1 to j, which becomes 1
console.log(arr[i][j]);//this shows the value of [1][1], which is ‘4’

/*the sub ‘for’ loop is now complete as arr[1].length matches the length of the sub array,
we then return to the first for loop, which is still initialised at [0] */

[2][j]//+1 is added to the first for loop
[2][0]//j is initialised to 0 again within the sub ‘for’ loop. this is because it completed its function last time after meeting the arr[1].length
console.log(arr[i][j]);//this shows the value of [2][0], which is ‘5’
[2][1]//the sub loop runs through again and adds +1 to j, which becomes 1
console.log(arr[i][j]);//this shows the value of [2][1], which is ‘6’

/*the sub ‘for’ loop is now complete as arr[1].length matches the ‘j’,
we then return to the first for loop, which is also complete as ‘i’ matches arr.length, and so the function stops running and completes */

The main thing I’m checking is how the sub ‘for’ loop returns to 0, is the variable sort of disposed of once it’s completed and then it’s reset to 0 when the topmost ‘for’ loop comes around again?

Sorry if this is all messy and confusing to look at, I usually have this within virtual studio code where I keep my notes.

Yes, every time the topmost loop runs, the variable in the inner loop is reset to 0.

1 Like