Unable to pass a JavaScript challenge

I am learning JavaScript with freeCodeCamp.org. I have a problem passing this challenge about replacing loops with recursion. Following the examples given, I have come up with the code below, but still unable to pass. The worst thing is, I can’t go forward.

function sum(arr, n) {

  // Only change code below this line

  function sum(arr, n) {

  if(n <= 0) {

    return 1;

  } else {

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

  }

}

  // Only change code above this line

}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

And please always provide a link to the challenge:

You have two issues here.

First, you’re defining

function sum(arr, n) {

twice, once inside the other.

When I fix that, you still have a problem but you are very close.

I think you need to think about this line:

    return 1;

Hint:

Using 1 as your base case (the first number that gets evaluated that you will be combining with the others) made sense in the example to generate a product. Right? Anything multiplied by 1 is itself. But that is not the case with sums, when you’re doing addition. What does that need to be?

Sending many thanks to you @KevinSmith.

1 Like

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