function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
After running the above code it returns an array [1, 2, 3, 4, 5] But push()
adds new values at the end of an array so when value of n was 5 it should push 5 to the end of the array and when value of n got 4 it should push 4 at the end of the array like [5,4]
. So why not it is returning [5,4,3,2,1]
? It is hard to understand what is happening in this code probably because of this recursion. Isn’t unshift()
(which add new values to start of the array) should return [1,2,3,4,5]
and push() [5,4,3,2,1]
why opposite is happening?