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
console.logcan also be your friend. But I'm not sure I understand your explanation of what's happening: Whencountup(n - 1)is hit the function is called again with the new value fornon entry.nwon't be less than one until... it's less than one, e.g., first time, it'll be4.countup, for each execution ofcountup.const countArray = countup(n - 1);doesn't throw the execution back to line 1! It makes another call tocountupwithn-1, once that call returns, the current invocation continues and returns it's own value.