Confused of ReferenceError: myArray is not defined

Tell us what’s happening:

Firstly, I tried a simple function, to check if it is working. It doesn’t, because ReferenceError: myArray is not defined

function countdown(myArray, n) {
  if (n <= 0) {
    return n;
  } 
}
countdown(myArray, -1);

I then manually changed myArray to be an empty array when I called the function. I got right outputs in the console, but can’t pass the challenge. Can someone help me to understand the error and how to handle it? Thank you!

Your code so far


//Only change code below this line
function countdown(myArray, n) {
if (n <= 0) {
  let arr = [];
  return arr;
} else {
  let newArr = countdown(myArray, n - 1);
  newArr.unshift(n);
  return newArr;
}
}

countdown([], 10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

The 1st function you had
1 was missing and else statment to complete it
2 was returing counting down myArray but not n

the second code
has allot of statments that aren’t completly necearly
you can write the code much simpler

for me it somethimes helps to write pseudo code :3
i want a function to countdown myArray and n

if it the n is less to 0 it should return

else myArray pushes the n paramenter

and countsdown minus one myArray as well as the parameter

1 Like

If you look carefully at the explanation of the challenge and the test requirements, the function countdown is not supposed to return a new array. It is supposed to modify myArray. You do not need to add a function call to your code. The tests will call the function.