Basic JavaScript - Replace Loops using Recursion

Hello, this is my code so far. When I run the test there are x’s for sum([1], 0) should equal 0 .
and for sum( [2, 3, 4, 5], 3) should equal 9.
How do I correct my code to complete this task.

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 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

You can add in console.log() lines for debugging:

console.log(arr[n-1])

Add this as test case at bottom:

console.log(sum([2, 3, 4, 5], 3))

Then,

  1. why use * when you are looking for sum.
  2. why return 1 when n <= 0 ?

return sum(arr, n - 1) * arr[n - 1];

if (n <= 0) {
  return 1;

gotchu. I figured it out added the + and changed return 1 to return 0. thanks

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