function countdown(n){
if(n<1){
return []
}else{
const arr = countdown(n-1)
arr.unshift(n)
return arr
}
}
console.log(countdown(5))
Here I don’t understand what this is and why it is needed (n-1)?
function countdown(n){
if(n<1){
return []
}else{
const arr = countdown(n-1)
arr.unshift(n)
return arr
}
}
console.log(countdown(5))
Here I don’t understand what this is and why it is needed (n-1)?
This is using a concept called recursion to return an array of numbers from the initial number to 1. Recursion is a programming concept where a method calls itself to perform a similar function with a slightly modified set of data.
In this case, the method is built to return an array of numbers that counts down from the starting number down to 1. It’s using the n - 1 as the “loop” by calling itself with one less than the n until it returns an empty array. Then it goes back “up” the loop, adding the n value to the START of the array using the array unset. Sorry, it’s confusing, but hopefully this chart will explain what it’s doing…
Sorry if that seems confusing, but that’s what that code does. And it shows the problem with recursion.
While recursion has it’s uses, it can be abused like in this case as it’s doing a lot of extra work just because someone doesn’t like to do a negative count loop. This code can be rewritten and be a lot less confusing (at least to my eyes)
function loopCount(n) {
let arr = []; // create an empty array
// starting with the value n, add it and each number less than (n - 1, n - 2. etc) down to 1
for (let i = n; i > 0; i--) {
arr.push(i); // add the value to the array
}
return arr;
}
So this code does this
Here are the two blocks of code in a codepen just to show they return the same values
Now I’m starting to understand a little
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.