Recursive CountDown

Tell us what’s happening:

Hi !

I have to do a countdown, but I don’t understand why my code doesn’t work.
Could someone explain me why, and what is he doing instead ?

Thank you very much !
Max,

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.88 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Some things that might help you:

  1. your declaration of array is undefined so you can’t call .push(n) on it. So you have to change that (look at the example declaration to help you out).
  2. Consider using the .unshift() method for reversing the count instead of .push().
1 Like

Thank you for your reply !
I defined the array, and I saw the solution with unshift,
but I would like to know what my script is doing instead of the right solution !

Well, as I said first of all it’s calling a .push() method on an “undefined” variable which throws and error and stops further execution.
If it’s recursion you are confused about, I recommend further reading on https://www.geeksforgeeks.org/recursion/. It’s not an easy concept to get your head around for most people (including me).

2 Likes

  var array; // create variable of value undefined 
  array.push(n); // you can't push to undefined 
  array = countdown(n-1); // overwrite array variable so anything above this (if there weren't errors) is cancelled
  return array;

1 Like