Understanding recursion Example

function countup(n) {
if (n < 1) {
return ;
} else {
const countArray = countup(n - 1);
// step 1 countdown(4)
// step 2 countdown(3)
// step 3 countdown(2)
// step 4 countdown(1)
// step 5 1 < 1 is true so
// step 6 countArray =
// step 9 countdown(2) is called
// step 12 countdown(3) is called
// step 15 countdown(4) is called
// step 18 countdown(5) is called
countArray.push(n);
// step 7 (1 is inserted into the array)
// step 10 (2 is inserted into the array)
// step 13 (3 is inserted into the array)
// step 16 (4 is inserted into the array)
// step 19 (5 is inserted into the array)
return countArray;
// step 8 [1] is returned
// step 11 [1,2] is returned
// step 14 [1,2,3] is returned
// step 17 [1,2,3,4] is returned
// step 20 [1,2,3,4,5] is returned
}
}
console.log(countup(5));

no question i had problems understanding the flow of the program so i posted it
for other people may find useful

thanks for your reply

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.