We call recursion or recursion when a function calls itself.
In a recursive function, each call is created in memory a new occurrence function with commands and variables "isolated" from previous occurrences, so a new scope for each function call. / p>
When the line x(n-1)
is executed, the current instance waits for a response of the new instance, ie, you must wait for the result of the x(n-1)
operation for the next operation to be performed.
In practice the following operations occur:
Call the function x(n)
.
Prints the value of n
(before) in the console.
Ends occurrence if n
equals 0
by returning a response to the previous instance (if any).
Cycle for
.
Prints the value of i
in the console.
Starts a new instance x(n-1)
(returns to point 2) and waits for the response.
Returns to point 4
if i < 3
.
Prints the value of n
(after) in the console.
Notice that at point 6
we create a new occurrence (n-1) and this causes the current occurrence (n) to wait for the response of the new occurrence before passing to the point 7
.
A step by step example for n=2
according to the scheme above:
1. x(2);
2. print "before, n: 2"
3. N > 0
4. For i=1
5. print "for i: 1"
6. x(1) //n-1 em que n=2
1. Iniciou uma nova ocorrência
2. print "before, n: 1"
3. N > 0
4. For i=1
5. print "for i: 1"
6. x(0) //n-1 em que n=1
1. Iniciou uma nova ocorrência
2. print "before, n: 0"
3. N <= 0
8. print "after, n: 0"
[Termina a ocorrência]
4. For i=2
5. print "for i: 2"
6. x(0) //n-1 em que n=1
1. Iniciou uma nova ocorrência
2. print "before, n: 0"
3. N <= 0
8. print "after, n: 0"
[Termina a ocorrência]
4. For i=3
8. print "after, n: 1"
[Termina a ocorrência]
4. For i=2
5. print "for i: 2"
6. x(1) //n-1 em que n=2
1. Iniciou uma nova ocorrência
2. print "before, n: 1"
3. N > 0
4. For i=1
5. print "for i: 1"
6. x(0) //n-1 em que n=1
1. Iniciou uma nova ocorrência
2. print "before, n: 0"
3. N <= 0
8. print "after, n: 0"
[Termina a ocorrência]
4. For i=2
5. print "for i: 2"
6. x(0) //n-1 em que n=1
1. Iniciou uma nova ocorrência
2. print "before, n: 0"
3. N <= 0
8. print "after, n: 0"
[Termina a ocorrência]
4. For i=3
8. print "after, n: 1"
[Termina a ocorrência]
4. For i=3
8. print "after, n: 2"
[Termina a ocorrência]
In the above list, I used spaces horizontally to simulate a new occurrence of the x
function.
If we only extract the lines in which "print" appears, we will have the following:
before, n: 2
for i: 1
before, n: 1
for i: 1
before, n: 0
after, n: 0
for i: 2
before, n: 0
after, n: 0
after, n: 1
for i: 2
before, n: 1
for i: 1
before, n: 0
after, n: 0
for i: 2
before, n: 0
after, n: 0
after, n: 1
after, n: 2
Although the first occurrence is x(2)
, after, n: 2
only appears at the bottom of the list because new occurrences appeared in the middle and fired console.log
before returning a response.