Can someone help me understand this code? Here is my understanding:
Let’s say we pass a value n=5
- n is not less than 5 so first if statement gets ignored
- in second statement countArray=countup(4) which calls the function again
- Function countup(4) now sets countArray=countup(3)
- It continues till countup(0) at which the first if statement runs and returns to countup(0) thus countArray=[ ]
- In next line the given n, 5, gets pushed to the end of the array countArray
- countryArray is now [5] which gets returned out of the function
I know I am understanding it wrong as the output is [ 1, 2, 3, 4, 5 ]
Can someone help me understand how we arrived to the output?
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]