Hey ahmed520,
I still remember when I learned about recursion for the first time. It was confusing for me too
A recursive function is a functon that calls itself again to calculate some result.
In your case, the function sum calls itself as long as “n” is greater than -1.
Let’s look into an example together:
sum([5, 3, 4], 2)
This function call should return 5 + 3 + 4 =12
Your JavaScript interpreter resolves this function call step by step like so:
sum([5, 4, 3], 2)
sum([5, 4, 3], 1) + 3
sum([5, 4, 3], 0) + 4 + 3
sum([5, 4, 3], -1) + 5 + 4 + 3
0 + 5 + 4 + 3
12
The recursion concept originates from math. In math, you can define a function recursively.
Take the factorial function for example.
factorial(n) = n * factorial(n-1) n > 0
factorial(0) = 1 n = 0
As you might see now, there are two essentials parts of a recursion:
(1) a part that computes something. This is the case n > 0 in our factorial example
(2) a termination condition. So a condition that when it becomes true stops the recursion. This is the case n = 0 in our factorial example
best
Dennis