I can’t wrap my mind around it. Explain it to me like i’m 5.
A lot of people are confused by this. Recursion is confusing.
how n counts up even though n is decremented.
Because you are pushing them onto a “stack”.
Imagine you are making a stack of plates. On the first place, you write “5” and put it down, the first plate in the stack. Then you take a plate, write “4” and put it on top of it. You keep doing that until you have 5 plates.
If you go to get a plate, what will the number be? “1”. This type process is called “last in, first out”, or LIFO. That is a characteristic of a stack. (A queue would be first in, first out, or FIFO.)
This is how recursion gets stored. When a new function is called, its information gets pushed onto the call stack. When its run gets interrupted (in this case by a recursive call) then a new function call gets pushed onto the call stack. So, at the end, you have 5 incomplete function calls on the stack. When that last one gets to complete, control goes to the last one in the stack, and so on, so from our perspective, it is “unwinding” itself by working though those function calls backwards.