Nesting For Loops javascript

Tell us what’s happening:
What am i missing?? can someone plz help me?

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[j];
     
    }
  }
  // Only change code above this line
  return product;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops/

What do you think is arr[j] there?

Remember that you are in a sub array, so you probably want to access the j element of i element of the array.

Consider this example:

  for (var i=0; i<arr.length; i++ ){ 
// let's say we are at i == 0
// so arr[i] == [1,2]

// now we loop into [1,2]
    for (var j=0; j<arr[i].length; j++){
// let's say we are at j == 0

      product*=arr[j]; // what is arr[j] ??
     
    }
  }

Hope it helps :slight_smile:

1 Like
     product*=arr[i][j];

I’ve solved it somehow but still kinda don’t get the logic.
is arr[i][j] only refers nested j array values inside of i array so you can multiply them?
then can’t i phrase it like arr.i.j as well? i tried but it didn’t work.
thanks.

The logic here is that arr is still the “original” argument that your function receive.

imagine a situation like this:

arr  = [  ['a', 'b'], ['c', 'd']  ]

If I want to print the values inside the sub array you still have to access them from the main array.

arr[0][1] // 'b'

// or
arr[1][0] // 'c'

that’s why I find it personally useful to give sub-values a variable name to make them clearer to read:

for(var i = 0; i < arr.lenght; i++) {
 var subArray = arr[i] // on each iteration subArray will change
 for(var j = 0; j < subArr.length; j++) {
    console.log(subArr[j])
 }
}
2 Likes