What is the meaning of this output?

What is the meaning of this output?
0

#1

hello,

I am logging this code and i don’t understand its logging what does it mean?


function multiplyAll(arr) {
var product = 1;

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

return product;
}
console.log(multiplyAll([[1,2],[3,4]]));

it logs : 11,23,4

Why?


#2

I will show you what the values of each variable are at various points in the function code. I will use your example of console.log(multiplyAll([[1,2],[3,4]]));

The function starts with product = 1

1st iteration of for loop - you attempt to concatenate product with arr[0]. arr[0] is [1,2] (an array with two elements 1,2). When you execute the line product += arr[i]; JavaScript tries to combine the array with the number 1 and ends up treating the array as string. When you combine a number with a string, the result is a string. In this case product is now equal to '11,2’. JavaScript evaluates this line as product = 1 + ‘1,2’ which results in the string ‘11,2’

2nd iteration of for loop - since product starts now as ‘11,2’ and you attempt to combine arr[1] (an array with two elements 3,4), the same thing happens as in the first iteration. JavaScript is treating the array as a string, so we end up with product = ‘11,2’ + ‘3,4’ which is the string ‘11,23,4’

The final value of product is ‘11,23,4’ and is returned to the calling function where the console.log statement displays this string to the console.

That is the explanation of why you have the strange result. The next question is “how do I fix my code?”

First, since you are supposed to multiplying the elements of the arrays to get a total product, you should be using the *= operator instead of the +=.

Second, you need to remember arr is an array of arrays (arr contains other arrays), so you will need 2 for loops (an outer to iterate over the nested arrays of arr and an inner to iterate over the the elements inside each nested array.

Note: To reference a nested array’s element, you will use the syntax of arr[i][j] where i is the outer array index and j is the nested array index. For example, if I have the following array:

arr = [ [1, 2], [3, 4] ];

and I want to reference the 3 inside the 2nd nested array, I would write:

var number3 = arr[1][0]; // 3 is assigned to the number3 variable

The first [1] represents the 2nd nested array and the second [0] represents the first element of the 2nd nested array.

See if you can now solve this challenge with this new insight into nested arrays.


#3

Thanks Randel for the explicit explanation. I know about the nested arrays and how to solve the challange, I didnt understand the outcome when i tried to add the elements of the outer array. Now I understand. Thanks!