THE TASK The function should use recursion to return an array containing the integers n through 1 based on the n parameter. If the function is called with a number less than 1, the function should return an empty array.
Im struggling with recursion and hoping for some clarification. If I remove this line countArray.splice(0, 0, n), then the log returns an empty array. Which would suggest that n < 0, which is obviously not true here.
I feel like let countArray = countdown(n - 1); should return [1, 2, 3, 4, 5] here, when the line countArray.splice(0, 0, n) is removed.
If that’s true, then why is it returning an empty array and how does adding countArray.splice(0, 0, n) OR countArray.unshift(n) invert the value of let countArray = countdown(n - 1);?
// Only change code below this line
function countdown(n){
if (n < 1) {
return [];
} else {
let countArray = countdown(n - 1);
countArray.splice(0, 0, n)
return countArray;
}
}
// Only change code above this line
console.log(countdown(5));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0
Challenge: Basic JavaScript - Use Recursion to Create a Countdown
Why would it do that? You never put anything in the returned array if you delete the splice.
If you never insert anything into the result array, then the result array will stay empty.
It doesn’t. Unshift or splice is only adding one value.
This is a function call. It must be resolved to a return value before the next line is executed. When n === 5, what should the result of this function call be?
Hey there, this is just a quick reminder that we want to keep this space safe and welcoming for all. Please keep your interactions with your fellow campers friendly and positive.
Its taken me a few days but I finally grasped what it is you’re saying and what’s going on here. But what I dont understand is, why cant I use .push here? Why is push returning [1, 2, 3, 4, 5] instead of [5, 4, 3, 2, 1]?
And why is this test failing: Global variables should not be used to cache the array - when the only thing I change is .push instead of splice or unshift? Im really loathing recursion.
Try and use some pen and paper to write down the function calls in order to understand how the result is being formed
(Assuming that you have a push to add n)
Dont push and unshift do the exact same thing, with the only difference being where one starts adding the data (beginning or end)? So if we are pushing or unshifting to an empty array, shouldn’t the results be the same? Since the end and beginning are the same?