Basic JavaScript: Replace Loops using Recursion -

I’ve looked at the solution and I still don’t understand how the code delivered to the solution.

Could somebody explain how the code runs each time it goes through the recursive statement? I understand it skips through the base code until n is less than or equal to 0.

Write a recursive function, `sum(arr, n)` , that returns the sum of the first `n` elements of an array `arr` .

And the solution was:

``````
function sum(arr, n) {

if (n <= 0) {
return 0;

} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
``````
2 Likes

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (`</>`) will also add backticks around text.

Note: Backticks are not single quotes.

3 Likes

Hey miochung, you almost got the solution yourself!
With recursions, the base step is the most fundamental part.
So what’s happening here:
As we see we have a function sum which is calling itself when the if statement is false.

What this means is the sum function calls itself until the if statement is true. You can see it as a domino game that we keep adding a domino as long as we hit else statement until we hit if.
When we get to if, or base step in recursion, our function only then returns an actual result which is 0 here. This is like the first domino tile falling.

Now is the interesting part having a value for the base step makes the step right before it to also have a value. Because that step right before has called sum function and that has resulted in 0 (note the arr[index] always has a value). In the dominos world the fall of first tile has made the second tile to fall.

When the step right before the last one is having a value, the step before that is also having a value (with the same reasoning as above). And as you have gusses with a domino analogy our dominos keep falling and making the domino tile set before them to fall. This goes all the way back to the first ever domino tile set which is … the first call of sum and that is now having a value.

Hope this helps to clear out some confusion.
Let me know if you had any questions and good luck!

1 Like

Thank you taking the time to respond!

I’m still confused what `sum(arr, n - 1) + arr[n - 1];` is referring to.

Would it be something like this?

``````sum(arr, n - 1) + arr[n - 1] would look like this below?

sum([2, 3, 4],  1) would become below

sum([2, 3, 4],  1-1) + arr[2-1]
``````

Could you let me know what the stack looks like when it goes through the recursive statement. What is the outcome before the domino tiles fall down to the first ever tile?

``````sum([2, 3, 4],  1) - the stack will look like this

skips the base call as n === 1

sum([2,3,4], 1-1) + arr[1-1]  - does this return the first element of array number 2 as array is now arr[0] from the subtraction?

sum([2,3,4], 0) stops at the base call and returns 0.
``````
1 Like

Hi,
Use the `console.log(arr);`
or/and `console.log(n);` to see what happen inside your function.
And check step by step the logged data on the console. This is the best way to understan the logic…

2 Likes

where do I console.log(arr) in the function? It keeps saying undefined…

Based on the example and the answer you have I think you got things perfectly right.
Yes `sum([2,3,4], 0)` stops at base and `arr[1-1]` returns the first element of the array i.e 2.

Hi,

Inside the function (in scope) you can log any variables, even the arguments.
You can add your personal hint too. It is really helpful to understand what happen behind the scene.

Option 1
``````"use strict";
function sum(arr, n) {
console.log("arr:", arr);
console.log("n:", n);
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}

console.log("sum() return:", sum([2, 3, 4], 1));
``````

Or more visible:

Option 2
``````"use strict";
function sum(arr, n) {
console.log("arr:", arr);
console.warn("n:", n);
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}

console.error("sum return:", sum([2, 3, 4], 1));
``````

Or maybe this is the best:

Option 3
``````"use strict";
let start = true;
function sum(arr, n) {
//    console.log("arr:", arr);
//    console.warn("n:", n);
if (start) {
console.log(`------- First call: --------`);
start = false;
} else {
console.warn(`Recursion:`);
}
if (n <= 0) {
console.log("return: 0");
start = true;
return 0;
} else {
console.log(`return: `, arr[n - 1]);
return sum(arr, n - 1) + arr[n - 1];
}
}

console.error("sum return:", sum([2, 3, 4], 1));
console.error("sum return:", sum([2, 3, 4], 2));
console.error("sum return:", sum([2, 3, 4], 3));
``````
2 Likes