return sum(arr, n-1) + (arr [n-1]);
I suppose the function returns the sum of the first N elements in given array.
EXAMPLE:
let’s make simple example var arr = [1, 2, 3], n = 3; and call the function
1st function call
function sum(arr, 3)
if (3 <= 0) {
return 0;
}
=> false
let’s move into the else section
return sum(arr, 3 - 1) here it pauses!!!
why? because we’re calling function sum(arr, 3-1) => sum(arr, 2)
2nd function call
function sum(arr, 2)
if (2 <= 0) {
return 0;
}
=> false
return sum(arr, 2-1) here it pauses!!!
why? because we’re calling function sum(arr, 2-1) => sum(arr, 1)
3rd function call
function sum(arr, 1)
if (1 <= 0) {
return 0;
}
=> false
return sum(arr, 1-1) here it pauses!!!
why? because we’re calling function sum(arr, 1-1) => sum(arr, 0)
4th function call
function sum(arr, 0)
if (0 <= 0) {
return 0;
}
=> true
AND NOW, we are going back to the 3rd function call and return 0 from this 4th function call
back to 3rd function call
return sum(arr, 0) + (arr [1-1]); => 0 + arr[0] => return 1
cause arr[0] = 1
now it takes 1 from it and place it as result of function call from 2nd function call
back to 2ng function call
return sum(arr, 1) + (arr [2-1]); => 1 + arr[1] => return 3
back to 1se function call
return sum(arr, 2) + (arr [3-1]); => 3 + arr[2] => return 6
RESULT = 6