Home > Net >  Recursions Javascript - Freecodecamp
Recursions Javascript - Freecodecamp

Time:07-19

beginner here. Was working through a code question on fcc and came across some javascript code I can't seem to understand.

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

  // Only change code above this line
}

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


// Console then spits out "9"

I understand how the second have of the return statement "arr[n - 1]" produces 4", but I'm unsure of how the first half "sum(arr, n - 1)" comes up with the number "5" that when added to 4, gives me the number "9" in the console.

I've narrowed it down to "sum(arr, 2)", but I can't seem to understand what the code is doing?

Thank you in advance!

CodePudding user response:

sum(arr,2) calls the same function "sum" with the same arr parameter and a limit that's 2 instead of 3.

While the first call (inside console.log) is supposed to add a number of parameters (3), the second call (inside the first) should add all parameters but the last one (2), which is added explicitely.

That's the point of recursion: a function that calls itself until a specific condition is met. The condition in this case is if there is no element left to be added (n<=0). Up to this all numbers appear as "arr[n-1]" in the chain of calls and are added to 0 (which is the return value in the case of the ending condition). So the actual sum is calculated as all recursive calls return one after the other.

  • Related