Syntactic explanation of this line of sum(arr, n - 1 ) + arr[n - 1]

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:

It isn’t a range.

The sum function is defined with two parameters:

function sum(arr, n) { ... }

The first parameter is an array, the second is a number.

So when you call the sum function recursively, you have to provide two arguments, an array and a number.

That’s what sum(arr, n - 1 ) is.

And, with every recursive call, the number n is reduced by 1.

Does that make a bit more sense?

1 Like

Using this Visualizer might help as well.

2 Likes

yeaaaah!!.. sum(arr, n - 1 ) is the recursive call of the original function, now I get it. :man_facepalming:

Thanks for taking the time and clarifying this for me.

Awesome, thanks for sharing this is really useful.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.