I’ve been trying to understand step by step what is happening in the example to create an array counting up from 1 to n. I’ve read all the forum posts over and over and it’s still not clicking.
The code is:
function countup(n) {
if (n < 1) {
return [ ];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
Using the example of n = 3, my understanding is that it executes to the line…
const countArray = countup(n - 1);
… which calls the function again (it jumps back up to the very first line). So basically it keeps (re)calling the function with 2, then 1, then 0 - the base case.
This is where my confusion is. As it recalls the function, are 2 and 1 being returned in an array? Or does it hit the base case, return an empty array, and then start working backwards, pushing 1 into the empty array, then 2, then 3?
The explanation on the page basically says an array of [1, 2, …(n - 1)] is returned just through the recursion - without ever having executed the…
countArray.push(n)
…line once. The .push() line only executes once and pushes n (in this case 3) onto the end of the array.
Another explanation/visualization on the forums makes it seem like .push() line is executed for every iteration of n, but only after the base case is reached. So it hits the base case, creates the empty array then for some reason works backwards, executing the .push() line with 1, then 2, all the way up to n.
Might be easiest to ask if the line…
countArray.push(n);
…is executed once at the end for n, or if in this case it would be executed 3x - pushing 1, then 2 then 3 into the array?
WARNING: I’m so new I don’t know if my question or explanations even make sense