Hey,
I’ve run this with debugger, also changed naming a bit, hope it will help you.
function sum(array, positionInArray) {
debugger;
if (positionInArray <= 0) {
return array[0];
} else {
return sum (array, positionInArray - 1) + array[positionInArray];
}
}
console.log(sum([2, 3, 9], 1));
First thing which happend is calling sum function and passing parameters.
Then we’re checking if second parameter which I changed to positionInArray is smaller or equal to zero if so we’re returning first element of array
if it’s greater then else is comming to play which passes to sum array[positionInArray] (console.log(sum([2, 3, 9], 1 this element exacly is equal to positionInArray)); )
That’s why with console.log(sum([2, 3, 9], 1)); you get 5, if you’d change it to console.log(sum([2, 3, 9], 2)) you’d get 14.
Sorry for typos english is not my primary language
Thanks so much for the reply. But can you show me how the math would add up to 14? Specifically can you explain what is happening in (array, positionInArray - 2) ?
Regarding that sum([2,3,9], 0) is 2 - take a look at the function, you have
if (n <= 0) {
return arr[0];
}
As function is sum([2,3,9], 0) and that’s sum(arr, n), then n = 0, resulting in returning first element (element with index 0) from the arr array, that’s 2.
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.
I think I am thrown off by the comma in (arr, n). Is the n after the comma finding the index of arr ? The only thing I am confused about is what is happening inside of the parentheses. Thanks so much for the help.