It Restart the variable "j" to 0 after it is false?

Tell us what’s happening:
Describe your issue in detail here.

I was able to finish the test but I feel a bitter taste because I do not understand why after the inner loop is false and then the first level loop is executed, the variable J happens to have the value of 0 and therefore each one can be multiplied of the values of the internal arrays.

  **Your code so far**

function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i= 0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++)
product *= arr[i][j];
// Only change code above this line
return product;

  **Your browser information:**

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

Challenge: Nesting For Loops

Link to the challenge:

Not sure what you’re saying. Each timethe outer loop increments, the inner loop should start at 0 again - thus, in the first sub-array (when i==0, so arr[0]), j is 0 for the first element in that sub-array, then 1 for the next.

That array complete, i increments and j resets to 0, giving you arr[1][0] and then arr[1][1]. And so on. i indicates which inner array, and j indicates which index in that array.

However, i would recommend not using var here. i and j don’t need to exist outside this block, so use let to block-scope them.

1 Like

I appreciate your answer, but I’m no pretty sure to understand why the inner loop resets to 0. Do I just have to understand it as a rule? … P.D. sorry about my English. And thanks by the advice about the var o let use.

On every single iteration of the outer loop (the i loop), you run the inner loop (the j loop). The inner loop explicitly says that it sets j=0 as the initialization step.

//   ↓-------↓ This is the initialization part of the loop
for (let j = 0; j < arr[i].length; j++) {
// The initialization *always* runs before the loop starts
//                                 ↓-↓ This is the incrementor part of the loop
for (let j = 0; j < arr[i].length; j++) {
// The incrementor runs after every loop iteration
//              ↓---------------↓ This is the exit condition
for (let j = 0; j < arr[i].length; j++) {
// The loop stops after the exit condition is met

Thanks a lot! I think I need a break before I continue studying!

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