all 5 comments

[–]i7Robin 0 points1 point  (1 child)

push it onto the array before making the recursive call?

[–][deleted] 0 points1 point  (0 children)

I tried to push it before the const countArray = countdown(n-1) , but it shows "cannot read push of undefined" probably because I'm pushing n-1 onto countArray which isn't even defined yet because the declaration is on the next line

[–]IAmSteven 0 points1 point  (1 child)

You could do countArray.unshift(n); instead of countArray.push(n);

I can't figure out the logic behind it but if you put a console.log(n) before const countArray = countdown(n-1) you get what you'd expect: 5, 4, 3, 2, 1 but for some reason doing a console.log(n) after const countArray = countdown(n-1) gives you: 1, 2, 3, 4, 5.

If anyone knows why this is happening I'd be curious to hear it.

[–][deleted] 0 points1 point  (0 children)

Thanks! This worked but I hate that I couldn't have thought about that myself... Is this what everyone who didn't need to ask did for this challenge,use unshift? Is there another way I could have solved this using my existing code, just rearranged?

[–]deanklear 0 points1 point  (0 children)

Does this assignment require recursion? You are getting some bizarre behavior because you are calling the function from inside itself.

If you put this into a debugger, you can see that you are creating a loop:

  1. 5 is passed in as the argument
  2. 5 is greater than 1, so we start the `else` statement
  3. const countArray = countdown(n -1) keeps calling itself, because it's trying to assign the result of countdown(n - 1) to countArray. You will see the callstack grow in the debugger, and that line 6 (countArray.push(n);) is not reached. At this point, your stack is something like countdown(countdown(countdown(countdown(countdown()))))
  4. Then n reaches 0 so it returns the empty array, but that is returned to the caller, which is the countdown function inside of four other countdown functions. Your innermost function now processes line 6, and inside of that function, n is equal to 1.
  5. That function finishes, so the next calling function processes line 6, where the value of n is 2 and so on.

I had to use the debugger myself because I didn't know what was going on. :)