I'm a beginner going through a JS tutorial and got stuck trying to understand the order of statement execution in this example of a recursive function:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // Output is [ 1, 2, 3, 4, 5 ]
I assumed, that each time const countArray = countup(n - 1);
line is reached, it throws the execution back to line 1 with decremented n
. That would explain the output array starting at 1 and going upwards, while n
is going down. But in that case, shouldn't the function just return empty array [], since n
would drop below 1, satisfying the first if
and terminating before anything having been pushed into countArray (else
)?
**Tried googling about the use of breakpoints to see the actual flow, but only saw their uses in non-loops