How loop become from 0 to 2 to 5 to 9?I don't understand

Tell us what’s happening:

Your code so far


function sum(arr, n) {
// Only change code below this line
 //return n <= 0 ? 0 : sum(arr, n-1) + arr[n-1]  ;
// Only change code above this line
// if (n <= 0) {
//     return 0;
//   } else {
//     return sum(arr, n-1) + arr[n-1] ;
//   }
let  product = 0;
for(let i=0;i<n;i++){
  console.log(product)
  product +=arr[i];
  //console.log(product)
}

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

It depends on how you are calling the function, but to have more information on how the loop is happening I would inject the variables in the console.log call. Like that:

for(let i=0;i<n;i++){
  console.log(`Before, i: ${i}, product: ${product}, arr[i]: ${arr[i]}`)
  product +=arr[i];
  console.log(`After, i: ${i}, product: ${product}, arr[i]: ${arr[i]}`)
}

I think that way things would be more clear.

1 Like

From your loop definition, the value of variable ‘product’ is going from 0 to 2 to 5 to 9 in 3 iterations of the loop.

The loop variable ‘i’ is going from 0 to 1 to 2 and is the index into the array element arr[0] because ‘i’ = 0 on the first loop iteration. arr[0] = value of 2 so product is 2 on first iteration. Second iteration starts with ‘i’ = 1, arr[1] value is 3, ‘product’ += 3 equals 5 since ‘product’ was 2. Third iteration ‘i’ is 2, value arr[2] = 4, ‘product’ += 4 is
9 since ‘product’ was 5. ‘i’ is now 3 and the loop exits because ‘i’ is no longer less than 3 .