Hi.
I want to comprehend syntactically what “( arr, n - 1 )” and "arr[ n - 1 ] "mean. I understand how recursion works under the hood but I can’t wrap my mind around what are the “values”. My guess is ( arr, n - 1) references a range, and arr[ n - 1 ] is the reference of an index of the array.
I come to this conclusion by logging first arr[ n - 1 ] then ( arr, n - 1 ), for the first log I get back the element of arr which is at index 2 (4). What confuses me is with (arr, 2), I get back the elements of arr and the number 2 and I don’t understand or see it possible for JS to accept that as a range.
Code so far
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1 ) + arr[n - 1];
}
// Only change code above this line
}
console.log(sum([1], 0));
console.log(sum([2, 3, 4], 1));
console.log(sum([2, 3, 4, 5, 6], 3));
//test
let arr = [2, 3, 4, 5, 6];
let n = 3;
console.log(arr[n - 1]);
console.log(arr, n - 1 );
Challenge: Replace Loops using Recursion
Link to the challenge: