I'm trying to learn some JavaScript from freecodecamp.org and I stumbled upon a recursion problem which I can't wrap my head around:
Instructions: Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.
function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
I understand the second part: arr[n -1] adding the item value
But I don't understand what the first part(sum(arr, n-1)) does, and how the arr parameter reacts.
Can anyone help?
Any help is appreciated!
Aucun commentaire:
Enregistrer un commentaire