Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
  return 1;
} 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/ Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

can anyone please help me understand recursion? it’s the Replace loops using recursion challenge?

Is this really the value you want to return? What would happen if I called your function as:

sum([1,2,3], 0);

Thank you turns out I only needed to return 0. So I need to return 0 in terms of itself which is 0(base case)? Also i dont understand the recursion sum(arr, n - 1) + arr[n - 1] does it mean for e.g 5 - 6, 5 - 6, 5 - 6 or 1 + 1, 1 + 1 , 1 + 1 ?

how do I know that the value of sum is 1, 2, 3?

Remember what the function is doing. It adds the first n numbers of the array arr. So you can’t know what the sum of [1,2,3] is unless you know what the value of n is.

1 Like

So, what the condition or code (arr, n -1) and arr[n -1] is constant unless the parameters are different? also will my initialized value always return the same value initialized?

I think I understand it a little better so ill only use recursion when n is less than and equal to 0? in cases where its more than 0 it will result in an infinite loop? I need to know this because I dont know in what other instances ill have to use it, maybe when i need to divide? or subtract?

arr and n are variables take the value of whatever you pass into them when you call the function:

sum([1,2,3], 3

arr would be [1,2,3] and n would be 3.

Using these initial values, when the first recursive call is made it would call the function as:

return sum([1,2,3], 2) + arr[2];
1 Like

Actually, when n <=0 then you don’t use recursion, you return 0. This is the base case in your code:

if (n <= 0) {
  return 0;

Look closely a the recursion in your function:

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

What is happening to the second value passed into sum each time?

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