Different solution

Continuing the discussion from freeCodeCamp Challenge Guide: Replace Loops using Recursion:
so this it my solution for this challenge:

function sum(arr, n) {
  // Only change code below this line

  if (n > 0 && n <= arr.length) {
    return sum(arr, n-1) + arr[n-1];
  } else if (n > arr.length){ 
    return "There are only " + arr.length + " items in array!";
  } else {return 0;}

  // Only change code above this line

console.log(sum([1, 3, 7], 3));

It’s working and pass the test, but I am wondering, if it’s 100% correct?

Good call on catching the n > arr.length case!

The last else is equivalent to else if(n<=0) here, so your answer is 100% correct.

1 Like

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