push()
function will return the new length as a number, not an array. As a result, when countdown(n-1)
reaches a point where it returns a number, it no longer has access to the .push()
method.
An alternative approach would be:
function countdown(n) {
if (n <= 0) {
return [];
} else {
const result = countdown(n-1);
result.push(n);
return result;
}
}
Another option is to use .concat()
instead of push()
:
function countdown(n) {
return n <= 0 ? [] : countdown(n-1).concat([n]);
}
Alternatively, you can use spread syntax:
function countdown(n) {
return n <= 0 ? [] : [...countdown(n-1), n]);
}
Keep in mind that using the latter two methods may result in a time complexity of O(n²)
due to the repeated copying of elements into a new array. For even greater efficiency than the push
solution, consider using a non-recursive function:
function countdown(n) {
return Array.from({length: n}, (_, i) => i);
}