Recursion countdown help

Please see my code below for recursion countdown. I see the output coming correctly in the console log. But it is not passing the tests for countdown(10) and countdown(5).
Appreciate your help.

  **Your code so far**

// Only change code below this line
var countArray = [];
function countdown(n){
if (n < 1) {
  return [];
} else {
  return countArray;
// Only change code above this line

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

The function should use recursion to return an array containing the integers n through 1 based on the n parameter.

Array should not be created outside of a function.
Function gets a number and returns an array without using loops of any kind - that’s all.

Welcome to the forums by the way. : )

  1. Remove the globally declared countArray.
  2. Correct the else case.

Here’s an illustration for countup.

countdown is very similar to countup.
Here’s a tutorial on freecode camp What is Recursion? A Recursive Function Explained with JavaScript Code Examples

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.


var myGlobal = [1];
function returnGlobal(arg) {
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  return myLocal;
} // reliable - always returns an array of length 2

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.