I don't understand recursion

Tell us what’s happening:

  **Your code so far**

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

// Only change code above this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

can anybody briefly explain to me how to do this challenge. there is no video too.

1 Like

Hey, this is my solution:

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.

Hope to help you.

1 Like

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


Oh, sorry I’m new in the platform

1 Like

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.


The issue has been resolved

There are also a few video walkthroughs of this challenge.

@ ryan.developer99 this video was very helpful

1 Like