Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
I have coded these and I am not sure how to make it to where the sum([1], 0) should equal 0. and * sum([2, 3, 4, 5], 3) should equal 9. passes. What am I missing that I need to put in or take out?

Your code so far

function sum(arr, n) {
  // Only change code below this line
if (n<=0){
return 1;
} else {
  return sum(arr, n-1)*arr[n-1]
}


  // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

that returns the sum of the first n elements of an array arr.

you need to sum the numbers from the array, not multiply.

I understand that but why does the one have to be a zero for the first return,

If you returned a 1 and added it to all the other n numbers from the array wouldn’t that be n numbers from the array added together + 1? The example code was for multiplying, which if you returned a 0 would just be 0 every time because of how multiplication works.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.