The problem is that you do not pass on the array to the recursive call, so each recursive execution creates a new, empty array. As a consequence, it does not return the array that had a value pushed to it, but the new, empty one that is coming back from the recursive calls.

Secondly, you never push value 1 to the array. So it would be better to stop the recursion at 0 instead of 1.

So taking those two fixes, you get this:

function countdown(n, newArr=[]) {
    if (n <= 0) {
        return newArr;
    }
    newArr.push(n);
    return countdown(n - 1, newArr)
}

console.log(countdown(5));

Your alternative solution is clean, because it does not need to pass an array as argument. It uses the returned array to add the next value to it (in front of it). It would have my preference.

To understand how it works, print out the intermediate values:

function countdown(n) {
  if (n < 1) {
    console.log("At the end of recursion. Creating and returning an empty array.");
    return [];
  } else {
    const arr = countdown(n - 1);
    console.log("Got the following array back from the recursive call:");
    console.log(JSON.stringify(arr));
    arr.unshift(n);
    console.log("Prefixing it with " + n + " and returning the result:");
    console.log(JSON.stringify(arr));
    return arr;
  }
}

var result = countdown(5);

Answer from trincot on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org › guide
freeCodeCamp Challenge Guide: Use Recursion to Create a Countdown - Guide - The freeCodeCamp Forum
December 3, 2019 - Use Recursion to Create a Countdown Solutions Solution 1 (Click to Show/Hide) function countdown(n) { if (n < 1) { return []; } else { const arr = countdown(n - 1); arr.unshift(n); return arr; }
🌐
DEV Community
dev.to › naveenkolambage › create-a-countdown-using-recursion-freecodecamp-notes-1k2m
Create a countdown using recursion (FreeCodecamp notes) - DEV Community
September 22, 2022 - Things to consider, if you have ... this as follows · function countdown(n, newArr=[]) { if (n <= 0) { return newArr; } newArr.push(n); return countdown(n - 1, newArr) } console.log(countdown(5)); So thats how you pass the ...
Discussions

Use Recursion to Create a CountdownPassed (JS Algorithm)
Question We have defined a function called countdown with one parameter (n). The function should use recursion to return an array containing the integers n through 1 based on the n parameter. If the More on stackoverflow.com
🌐 stackoverflow.com
May 3, 2020
Using recursion to create a countdown in Javascript
To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
8
1
July 21, 2021
python - Recursion countdown - Stack Overflow
I'm working on this recursion function that takes in a number and counts down. So the first attempt gave me 0 followed by 'None' n times, my Second attempt threw a RecursionError:maximum recursion ... More on stackoverflow.com
🌐 stackoverflow.com
Basic JavaScript - Use Recursion to Create a Countdown
function countdown(n) { if (n 5? Also, can someone walk me through a scenario of each line for example if n was equal to 4? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
November 1, 2023
🌐
DEV Community
dev.to › rthefounding › using-recursion-to-create-a-countdown-59gp
Using Recursion to Create a Countdown - DEV Community
April 25, 2021 - For example, calling this function with n = 5 should return the array [5, 4, 3, 2, 1]. Your function must use recursion by calling itself and must not use loops of any kind. ... function countdown(n) { if (n < 1) { return []; } else { var ...
Top answer
1 of 4
4

The problem is that you do not pass on the array to the recursive call, so each recursive execution creates a new, empty array. As a consequence, it does not return the array that had a value pushed to it, but the new, empty one that is coming back from the recursive calls.

Secondly, you never push value 1 to the array. So it would be better to stop the recursion at 0 instead of 1.

So taking those two fixes, you get this:

function countdown(n, newArr=[]) {
    if (n <= 0) {
        return newArr;
    }
    newArr.push(n);
    return countdown(n - 1, newArr)
}

console.log(countdown(5));

Your alternative solution is clean, because it does not need to pass an array as argument. It uses the returned array to add the next value to it (in front of it). It would have my preference.

To understand how it works, print out the intermediate values:

function countdown(n) {
  if (n < 1) {
    console.log("At the end of recursion. Creating and returning an empty array.");
    return [];
  } else {
    const arr = countdown(n - 1);
    console.log("Got the following array back from the recursive call:");
    console.log(JSON.stringify(arr));
    arr.unshift(n);
    console.log("Prefixing it with " + n + " and returning the result:");
    console.log(JSON.stringify(arr));
    return arr;
  }
}

var result = countdown(5);

2 of 4
2

You need to hand over the result array for the recursive call. And you need to check if no value is left, ten return the result array.

function countdown(n, result = []) {
    if (n < 1) return result;
    result.push(n);
    return countdown(n - 1, result);
}

console.log(countdown(5));

As another approach, you could return an array and for the exit condition take the final value, otherwise take n and the spreaded result of the recursive call.

function countdown(n) {
    if (n < 1) return [];
    return [n, ...countdown(n - 1)];
}

console.log(countdown(5));

🌐
Reddit
reddit.com › r/learnprogramming › using recursion to create a countdown in javascript
r/learnprogramming on Reddit: Using recursion to create a countdown in Javascript
July 21, 2021 -

Hi guys, I am stuck on a very simple recursion problem where I am asked to use recursion to count down from n and log each number. The prompt is as follows:

"Write a recursive function that accepts a positive integer n as an input and logs every number from n (inclusive) to 0 (exclusive) to the console"

And here is my attempt:

function countDown (n) {

//base case

if (n <= 0) { return 0}

// recursive call

else { countDown (n-1)

console.log(n)

}

Trying to figure out where I am going wrong here and I appreciate any feedback. Thanks!!!

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Use Recursion to Create a Countdown - JavaScript - The freeCodeCamp Forum
November 1, 2023 - function countdown(n) { if (n < 1) { return []; } else { const arr = countdown(n - 1); arr.unshift(n); return arr; } } So I understand what the code is doing and got it to run. However, I am still …
Find elsewhere
🌐
Computer Science Circles
cscircles.cemc.uwaterloo.ca › 16-recursion
16: Recursion | Computer Science Circles
5 4 3 2 1 Blastoff!Here is a program that uses recursion to achieve the same effect. Let's add some extra print statements to help us understand how the program works. This version of the program also reads the time limit from input. If you like, use Enter input with the above program to try other input values. Try 0 first and see what happens, and then 1. When the input is 5, the program first calls a copy of the countdown function with n=5, which prints 5 and calls countdown(4).
🌐
Reddit
reddit.com › r › FreeCodeCamp › comments › gtf4lh › basic_javascript_use_recursion_to_create_a
r/FreeCodeCamp - Basic JavaScript: Use Recursion to Create a Countdown
May 31, 2020 -

hello everyone,I'm having a hard time understanding how the code from this exercise works, i tried using debugger but I got more confused

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 ]

what I understand so far is that the function countup(5) gets executed then the recursion keeps happening till n=0

if (n < 1) {return [];}

now we have an empty array and that's all I understand😅

1.why am I not kicked out of the if statement after that, how does the function keeps executing??

2.the function then start pushing the numbers incrementally, what causes the increment here?? Also when I the debugger I noticed that the function would hit the last curly bracket and then jump back tocountArray.push(n); how does that happen .. any clarification would be appreciated

Top answer
1 of 3
2
  1. That if clause is checking whether the argument is less than 1. If you’ve passed in 5, that’s more than 1 so the if block is never executed.

  2. This is the recursion part. The thing to think about is that the code block will recur until the if clause is met, which returns an empty array. So the first line of the else cause is what will execute recursively. This returns an empty array which then has all of the numbers pushed into it as the blocks of code from each prior recursion get executed.

I’m not a huge fan of this sort of recursive pattern because it values brevity over clarity. In most real world circumstances, the marginal reduction in computational overhead will be of no benefit if others working on the code have a hard time understanding it.

2 of 3
2

the return happens when n<1.

As far as how the recursion works, it happens on the first line of the else block. You create a variable and assign it the value of executing countup with (n-1). You can't go to the next line until this line has resolved.

So what happens? you run another instance of countup, this time with n-1. If that n is now less than 1, it'll return the empty array, and you don't hit the else block, meaning you don't execute countup again.

At that point the countup inside of your countup returns []. You do get kicked out of the if statement, but it's the inside countup, meaning there's still the outside countup, where you were figuring out what countarray is. Now that we know that countArray is [], we can push n to that array and return it.

🌐
Instructables
instructables.com › teachers › coding
How to Write a Simple Countdown Recursive Function in Python : 10 Steps - Instructables
October 19, 2020 - How to Write a Simple Countdown Recursive Function in Python: A recursive function is a function that calls itself. Recursive functions are an important concept in the programming world. There are many situations where you might find yourself being able to use a recursive function to solve a problem that would…
🌐
Codecademy Forums
discuss.codecademy.com › web development
Did you make a recursive call to countDownRecursive() with count decremented? - Web Development - Codecademy Forums
April 27, 2023 - Using what you know of recursion, create a recursive version of countDownIterative() by completing the function countDownRecursive() so that it uses recursion instead to count down. function countDownIterative(count) ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript #112: Use Recursion to Create a Countdown - JavaScript - The freeCodeCamp Forum
June 8, 2022 - In the example function: function countup(n) { if (n < 1) { return []; } else { const countArray = countup(n - 1); countArray.push(n); return countArray; } } console.log(countup(5)); // returns [1,…
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Use Recursion to Create a Countdown: why does it increase?
April 19, 2020 - 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 ] …
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Use recursion to create countdown help
January 11, 2020 - Hello Guys , this is my code : const myArray = []; function countdown(myArray, n) { if (n <= 0) { return; } else { myArray.push(n); countdown(myArray, n - 1); } return myArray; } countdown(myArray, …
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript: Use Recursion to Create a Countdown #2 - JavaScript - The freeCodeCamp Forum
April 29, 2020 - Tell us what’s happening: ... [5, 4, 3, 2, 1]` Your code so far function countdown(n) { if (n < 1) { return ; } else { const arr = countdown(n - 1); arr.unshift(n); ......
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Create a Countdown by recursion
January 20, 2021 - Tell us what’s happening: i don’t quiet understand const countArray = countup(n - 1); => 5, 4 , 3, 2, 1 ""minus 1 with every loop"" countArray.push(n); => the .push() will add the value of …
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Use Recursion to Create a Countdown - Where does array come from?
February 1, 2022 - Tell us what’s happening: Describe your issue in detail here. // SPOILER Answer is CORRECT in the Basic Javascript portion - Use Recursion to Create a Countdown: I got the answer correct, by trial an error. However, I…