JavaScript recursion related question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript recursion related question

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 is 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?

27th May 2022, 3:30 PM
RD Singh
RD Singh - avatar
1 Answer
0
It enters the recursion BEFORE adding anything. If countup(4) returns [1,2,3,4], then coutup(5) firsts creates [1,2,3,4] and pushes 5 to result in [1,2,3,4,5].
27th May 2022, 3:36 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar