# Use Recursion to Create a Countdown: why does it increase?

This is the code:

``````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 ]
``````

Lesson: this seems counterintuitive since the value of `n` decreases , but the values in the final array are increasing . This happens because the push happens last, after the recursive call has returned. At the point where `n` is pushed into the array, `countup(n - 1)` has already been evaluated and returned `[1, 2, ..., n - 1]` . QUESTION: I don’t get it why does it increase? could someone give me another example? it decreases, because n-1!

because when it is in
const count Array = count up (n - 1);
re-enter the countup (n) function and do not go to the next line of code that would be countArray.push (n); until it find
if (n <1) { return ;}
and returns with the last one Array = count up (n - 1) with which he stayed.

``````
function countup(5) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);//[1,2,3,4]
countArray.push(n);//[1,2,3,4,5]
return countArray;
}
}

function countup(4) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);//[1,2,3]
countArray.push(n);//[1,2,3,4]
return countArray;
}
}

function countup(3) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);//[1,2]
countArray.push(n);//[1,2,3]
return countArray;
}
}

function countup(2) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);//
countArray.push(n);//[1,2]
return countArray;
}
}

function countup(1) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);//[]
countArray.push(n);//
return countArray;
}
}

function countup(0) {
if (n < 1) {
return [];// return []
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
``````
1 Like