countup(5) {
const countArray = countup(4) {
const countArray = countup(3) {
const countArray = countup(2) {
const countArray = countup(1) {
const countArray = countup(0) {
return [];
countArray.push(1);
return countArray; //[1]
countArray.push(2);
return countArray; //[1, 2]
countArray.push(3);
return countArray; // [1, 2, 3]
countArray.push(4);
return countArray; // [1, 2, 3, 4]
countArray.push(5);
return countArray; // [1, 2, 3, 4, 5]
}
If you look here, you can see that what we want to do is:
countup(5) {
const countArray = countup(5 - 1);
countArray.push(5);
return countArray;
}
The problem is, countArray isn’t exactly an array… It is a function call that will end up returning an array. So, the computer has to figure out what that array is before we can push anything to it. Now we have:
countup(5) {
const countArray = countup(4) {
const differentCountArray = countup(4 - 1);
differentCountArray.push(4);
return differentCountArray;
countArray.push(5);
return countArray;
}
As you can see, we run into the same problem: instead of an array, we have a function call. The computer will keep calling the function, with n
getting 1 lower every time. When n = 1
, countArray = countup(0)
. Since countup(0)
returns []
, when n = 1
, countArray = []
.
countup(1) {
countArray = countup(0); // = []
countArray.push(1);
return countArray; // [1]
}
Then ‘1’ is pushed into that countArray
and it is returned. Which means that countup(1)
returns [1]
. So,
countup(2) {
const countArray = countup(1); // = [1]
countArray.push(2);
return countArray; // [1, 2]
Then we go all the way back up until we reach the original call:
countup(5) {
const countArray = countup(5 - 1); // = [1, 2, 3, 4]
countArray.push(5);
return countArray; // [1, 2, 3, 4, 5]