Help with recursion and zero based indexing(mass confusion)

please, if you really want to understand, make a cup of your favorite tea, open this link https://javascript.info/recursion and read it, you’ll understand this simple concept before the tea gets cold

what does my function do with these?
sum([1], 0) should equal 0.

sum([2, 3, 4], 1) should equal 2.

sum([2, 3, 4, 5], 3) should equal 9.

in other words with the “return sum(arr, n-1) + (arr [n-1]);”

how does it plug these numbers in and get the answers.?

Try it yourself :smile_cat:!!! If you don’t understand, do the same, use console.log(),and watch the progress. Grab paper and pencil and go through each line as a computer!

let counterX = 1;
let counterY = 1;
let array = [];
function sum(arr, n) {
    console.log(`${counterX}. iteration down, n=${n}`);
    counterX++;
    if (n <= 0) {
        console.log("We've hit our condition = 0, we are returning up to the first iteration now!")
        console.log(`${counterY}. return back up - sum = ${arr[n]}`);
        counterY++;
        return 0;
    }
    else {        
        let x = sum(arr, n-1) + arr[n-1];
        array.push(x);
        console.log(`${counterY}. return back up - sum = ${arr[n-1]}+${arr[n]}`);
        counterY++;
        return x;
    }
}

//sum([1], 0) //should equal 0.

//sum([2, 3, 4], 1) //should equal 2.

//sum([2, 3, 4, 5], 3) //should equal 9.

2 Likes