Hi everyone! I am trying to wrap my head around recursion. As I understand it, every recursion call gets saved to the stack until it reaches the base case. Then all the returns from the recursion come into play.
That´s why recursion turns things on its head, like this example that sums values in an array?:
// Creates an array
const range = (start, end) => {
if (end === start) {
return [start];
} else {
var numbers = range(start, end - 1);
numbers.push(end);
return numbers;
}
};
// Sum numbers in array
const sum = (array) => {
if (array.length === 0) {
return 0;
} else {
console.log(array);
var recursion = array[0] + sum(array.slice(1));
console.log(array);
return recursion;
}
};
console.log(sum(range(1, 10)));
This is the output:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 4, 5, 6, 7, 8, 9, 10 ]
[ 5, 6, 7, 8, 9, 10 ]
[ 6, 7, 8, 9, 10 ]
[ 7, 8, 9, 10 ]
[ 8, 9, 10 ]
[ 9, 10 ]
[ 10 ]
[ 10 ]
[ 9, 10 ]
[ 8, 9, 10 ]
[ 7, 8, 9, 10 ]
[ 6, 7, 8, 9, 10 ]
[ 5, 6, 7, 8, 9, 10 ]
[ 4, 5, 6, 7, 8, 9, 10 ]
[ 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
55
What I don´t understand is how the first number is 10 when adding the numbers together:
10
19
27
34
40
45
49
52
54
55
Why do we get 10 as the first number?
The code says array[0] + sum(array.slice(1)), and all I can come up with is:
- If array[0] is 1 and array.slice(1) is 10: 1 + 10 = 11
- If things are turned on its head and array[0] is 10 and array.slice(1) is 10: 10 + 10 = 20
- If array[0] is 1 and array.slice(1) is 1: 1 + 1 = 2
Thanks for your help!