A question of scope and a loop

In the code below I start with a multidimensional array (arr [i][j]) and try to produce (1) the product of all numbers in the array and (2) the array (productArr) of all entries’ product in one dimension. If I place console.log(productArr) (line 14) inside the “for-loop” for j parameter, console.log(productArr) displays the productArr array which, of cause, is updating with each step. However, if I place console.log(productArr) at the end of function (line 19) I get no outcome. What is going on?

let productArr=[];
let productArrTemp = 1;

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++){
productArrTemp= productArrTemp*arr[i][j];
product *=arr[i][j];
console.log(productArr); // works fine
productArrTemp = 1;
// Only change code above this line
return product;
console.log(productArr); // does not work!

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

1 Like

Hi Sunshine
Are you sure is not working? In mine Browsers console I got 5040.

1 Like

Just before console.log(productArr), you return product. The function returns on that line, so the rest of the code is a dead code, therefore does not run. When you return from a function, whatever after that line will not run. Hope this helps.


the issue resolved. Many thanks, Eda

You’re very welcome. I’m glad it helped!