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.
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).
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;