function sum(arr, n) {
if (n === 0) return 0 //validates if is zero
if (n === 1) return arr[0]; //when n is 1 return the first element of array
arr[0] = arr[0] + arr[1]; // set the array first element as the sum of the current first element and the next element => [2, 3, 4, 5] = [2 + 3, 3, 4, 5]
arr.splice(1, 1); //remove the next element => [5, 3, 4, 5] = [5, 4, 5]
return sum(arr, n - 1); //call the function with the new array and n - 1
}
Recursion is calling the same method but changing params every call, in this case i am changing array and n state every time i call the method again. I sum the first element of the array with it next and remove the next, then i call the method subtracting 1 to n, when n = 1 returns the first element in this case the sum of the first n elements of the array.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions
Hey, I was in the same situation when I studied recursion.
So I googled it and watched this video.
He explains the basic concept of recursion pretty easily.
Hope this video would help you understand.