In recursions you call your function in your function until a given requirement is fulfilled.
In this case, your function requires an array as input and the given index where to start (normally this should be the length of the array - 1).
F.e. call the function sum([1,2,3,4], 3)
.
It checks if your index is at position 0, which is not the case.
Then it adds the item at the given index arr[3] = 4
to the same function, but with an index 1 lower: sum([1,2,3,4], 3) = sum([1,2,3,4], 2) + 4
The next function adds its index arr[2] = 3
to the sum to the same function of index 1: sum([1,2,3,4], 2) = sum([1,2,3,4], 1) + 3
. If you fill this in your first function call it becomes: sum([1,2,3,4], 3) = sum([1,2,3,4], 1) + 3 + 4
The next function adds its index arr[1] = 2
to the sum to the same function of index 0: sum([1,2,3,4], 1) = sum([1,2,3,4], 0) + 2
. If you fill this in your first function call it becomes: sum([1,2,3,4], 3) = sum([1,2,3,4], 0) + 2 + 3 + 4
In this case of n = 0
, it returns just the value of the array at index 0. value of the array in that index: sum([1,2,3,4], 0) = arr[0] = 1
So the total function adds up tosum([1,2,3,4], 3) = arr[0] + arr[1] + arr[2] + arr[3] = 1 + 2 + 3 + 4 = 10