# Explain nesting for loops

Hi all,
I have a few questions regarding the answer to the nesting for loops challenge.

I just would like a better explanation. (Spoilers below)

in regards to the i++ and j++ why is this necessary, where does the challenge say we have to add by one - dont get this at all.

Can someone please explain why we have to multiply the product to the array? As in product = product * arr[i][j] why cant we just assign product = arr[i][j]? As product is equal to 1 so why would it make a difference?

Why are we multiplying arr[i][j] and not just the whole element arr[i] to another arr[i]?

thanks guys for any responses- starting to feel like javascript is way too difficult for me

Hi! Can you please add a link to the challenge so its easier for others to understand the problem youâ€™re facing.

As for the nested for loops, they are used when you want to traverse nested arrays or create 2 dimensional arrays.

Here you are basically doing Y times of work for reach X
for example if you have this code.

``````for(let i = 0; i < 2; i++){
for(let j = 0; j < 2; j++){
console.log( i, j )
}
}
``````

the result you will get is

``````0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
``````

This is because when the outer loop starts, the value of i is 0 and then you enter the inner loop, and you have to finish the inner loop which is why it will keep the value of i at 0 but the value of inner loop will keep iterating until the condition is false, then the next iteration of the outer loop starts and then the same thing happens in the inner loop, the inner loop outputs values from 0 to 2 and the value of outer variable i remains at 1.

Hope this helped!

1 Like

Learn Basic JavaScript: Nesting For Loops | freeCodeCamp.org
heres the link to the challenge!

I just checked your code, if you do this, you wonâ€™t be saving any values to the product variable because in js and most of the programming languages, = does not mean â€śequals toâ€ť . It is the assignment operator and if you try

``````product = arr[i][j]
``````

you are literally telling it to assign whatever is inside the iâ€™th arrayâ€™s jâ€™th position on every iteration of the loop. so if you take the example you are given

``````multiplyAll([[1,2],[3,4],[5,6,7]]);
``````

on the first iteration, the value of arr[0][0] is 1 so by doing

product = arr[0][0] you are setting the product variableâ€™s value to 1

on the next iteration, the value of arr[0][1] will be 2 so instead of multiplying with the value inside the product, you are resetting the value of the product variableâ€™s value to 2.

and if you keep resetting the values you will eventually get to 7.

1 Like

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