Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
Describe your issue in detail here.
I got the code right but i do not understand the code
How does this work?
return sum(arr, n-1) + arr[n-1]
Your code so far

function sum(arr, n) {
  // Only change code below this line
 if(n <= 0){
    return n;
  } 
  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 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

1 Like

We have blurred this solution with [spoiler][/spoiler] tags so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

Whoever wrote the solution should know - ask him.

1 Like

I wrote the solution based on the example given.

So it sounds like it is the larger issue of not understanding recursion.

That is very common. Recursion is weird. There have been many, many, many discussions about it in the forum, many on this exact questions, some with detailed explanations, some even by me. I would suggest search those first.

But like I said, it is a tricky subject. Don’t be discouraged if it takes a while to wrap your head around it.

1 Like

Hi @andazi and welcome

You can use this tool to visualizing your code running Python tutor (it works with other languages too)

Remember call your function too, for example sum([2, 2, 2, 2], 2).

It is always helpful read different examples and explanations. The best two pages as reference are MDN Web Docs and this one Recursion and stack

A recursive function is like a family tree, you call the function and that function call another one with different arguments and so on (going down). After, the function start to run from the last one (with the last possible arguments) to the started point (going up in the tree). Every returning value it will be use for the parent function as keep going up.

I hope that helps

1 Like

Hello @andazi.

In order to understand this lesson, it is useful to analyze the information provided in more detail:

  • The name of the lesson is “Replace Loops using Recursion”
    This implies that they are very similar

  • There are 2 examples of the function multiply:

    • multiply using a for loop (left)
    • multiply using recursion (right)

  • The lesson states that:

multiply (for loop,left) vs multiply (recursion, right):

what are the differences between the 2 versions of multiply?


Note:
I have made a video explaining (step by step) this lesson freeCodecamp: "Replace Loops Using Recursion", Solution. - YouTube .

1 Like