I still dont get this recursion example...
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion
I don't understand why we get 9 and not zero when n is 0.
function sum(arr, n) {
// Only change code below this line
if(n ...
hashnode.com
because it's and addition in the end.
although I would use
const arr = [2,3,4,5]; console.log(sum(arr, arr.length));-> sum: [2,3,4,5], 3 - 3 > 0 - return sum([2,3,4,5], 2) + 4 -> sum: ...., 2 - 2 > 0 - return sum(....., 1) + 3; -> sum: ....., 1 - 1 > 0 - return sum(...., 0) + 2 -> sum: ....., 0 - 0 == 0 - return 0which means:
first call (4) + second call (3) + third call (2) + forth call(0) 4+3+2+0 -> 9;does this make sense?
a more visual approach would be if you just pop the value before passing
const val = arr.pop(); return sum(arr, arr.length) + val;but since JS an array is just a specialized form of an object you actually would need to
const newArr = [...arr]; const val = newArr.pop(); return sum(newArr, newArr.length) + val;to have no sideeffects. But this maybe is more confusing. it's just so the array you pass in as a reference does not get changed but you still see that the recursion your wrote basically is a stack call that removes one element after another and passes it to the previous call.
a question of taste so to say.