+ 1
why the output is 1,2,3,4,5 but not 5,4,3,2,1
6 Answers
+ 3
The reason itâs going from 1-5 instead of 5-1 is because the countup method is pushing n into the back of the array.
Because countup(n - 1) gets called recursively, the array push doesnât progress until the last call triggers (if n < 1).
When then processing is resumed, the inner most (last) recurse is finished first. So it works in then out.
A visual:
countup(5) {
countArray = countup(4) {
countArray = countup(3) {
countArray = countup(2) {
countArray = countup(1) {
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]
}
+ 3
Try to use
countArray.unshift(n)
coz push add at end means
example
1
now add 3
13
using unshift
1
now add 3
3 1
unshift add to front
+ 2
Mr. 12
I'd like to know why it behaves like that in a recursion too, it's a good question and I hope there's someone with answers
+ 1
HrCoder i know that methods, but if i start from 5 shouldn't it be adding the 5 first to the array and then n - 1 which is 4 now the array has [5, 4] ? not like this? i'm a bit confused here!
+ 1
...maybe more simple way of explaining:
Countup5 then calls
Countup4 then calls
Countup3 then calls
Countup2 then calls
Countup1 (return)
Countup1 finishes (pushes 1)
Countup2 finishes (pushes 2)
Countup3 finishes (pushes 3)
Countup4 finishes (pushes 4)
Countup5 finishes (pushes 5)
0
console.log(countup(5).reverse())
Try this