Hello everyone,
I’m trying to understand better the concept about Recursion,
function count(n) {
if (n === 1) {
return [1];
} else {
var numbers = count(n - 1);
numbers.push(n);
return numbers;
}
}
count(5);
The steps:
a. The function counting backwards, from 5
to 1
.
b. When 1 === 1
is true
, the function return [1]
and assign it to var numbers
.
c. numbers.push(n)
pushing the call stack to numbers
.
(starting from the last execution 2
to the first execution 5
).
d. Then the function return the value:
return numbers
console.log(numbers)
[1, 2, 3, 4, 5]
I got it right?