Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
I got this solution from the guide and I don’t understand this specific part of the solution:

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

why is there a need to subtract 1 from n?

Your code so far

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
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

En este ejercicio, al aplicar recursión vas a ir reduciendo el array hasta que desaparezca.
Por ejemplo:
sum([1,2,3],2) //Quieres sumar los 2 primeros números del arreglo.
sum([1,2,3],2) = sum([1,2,3],1) + arr[1] //‘arr[1] = 2’
sum([1,2,3],2) = sum([1,2,3],1) + 2;
sum([1,2,3],2) = sum([1,2,3],0) + arr[0] + 2; // ‘arr[0] = 1’
sum([1,2,3],2) = sum([1,2,3],0) + 1 + 2; //como “n <= 0” entonces sum([1,2,3],0] retorna 0;

sum([1,2,3],2 ) = 0 +1 + 2 = 6

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