Nested Loops Error - cant understand why

Nested Loops Error - cant understand why
0

#1

Hello,
I am doing the Nested Error problem on Javascript section.
im quite sure its correct, but its returning
“Cannot read property ‘3’ of undefined
Cannot read property ‘3’ of undefined
Cannot read property ‘3’ of undefined.”

i dont understand why, could someone explain it to me?
this is my code.


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

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);


#2

Right.

Take a look at what you did here. After exiting your nested forloops, values of i and j are three and they are trying to access arr value at arr[3][3], which is undefined.

I would do the calculations inside your nested loops and once you have the product, return it at the end of your function.


#3

Thanks for your answer.
Just to check if i understood correctly.

for (var j = 0; j < arr[i].length; j++){
var product = product * arr[i][j]
}

after the function run the first array (i) , it will jump into running J (thats also an array). after running J, it will set variable product (that was pre set in the beginning of the function) equals to product times the array I times the array J ?

ive tried running multiplyAll([
[2,2],
[3,3]
[4,4]
])
and the outcome is “Cannot read property ‘length’ of undefined”.

Could you try to explain it to me ?

Thank you!


#4

Actually, you would put that statement into the nested loops so that you have varying values at everyloop.
Also, you don’t want to declare var everytime because it will reassign new values everytime instead of multiplying itself over and over.

I would initialize product before forloops.

Can you also format your code? It’s hard to read them.