Noob question about Basic JS / recursion & Countdown

Hey all,

I’ve just started learning JS. I don’t understand how parts of the code in this lesson about recursion works:

I’ve read through the hints and also other posts on the forum, but I still don’t understand parts of the code and what happens when it is executed. This is the code:

function countup(n) {
  if (n < 1) {
    return [ ];
  } else {
    const countArray = countup(n - 1);
    return countArray;

And my questions:
Question 1: I don’t understand what happens when control has reached „countArray.push(n);“ I wonder where n is pushed to because there is no array existing yet.

Question 2: Also I wonder what this function returns (line7) concretely after the first loop when n is e.g. 5. Is it „countup(4)“? I don’t think that this is correct.

Question 3:
What happens when n reaches a value of 0 – I think the code „return [];“ is executed so an empty array is returned. But this is obviously wrong. What am I missing?

I will be so happy as soon as I’ve understood this. I would be very happy if yomebody could help me.


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thanks a lot :slight_smile: I absolutely will do in the future!

1 Like

Toss the code in here and see it working, it will help answer all those questions. JavaScript Tutor - Visualize JavaScript code execution to learn JavaScript online

Q1: countArray.push(n) is waiting in line basically. First we need to know what countArray equals. And since our base case has a return of an empty array, countArray will eventually equal and empty array that we can push to when n < 1, because we keep calling countup(n - 1).

Q2: Its returning an array that is eventually stored in countArray.

Q3: It is returning an empty array, then our countArray will finally be an array we can push to with our base case.

If you still have questions feel free to ask, recursion can be annoying to figure out.

Awesome!!! Thanks a lot!! :slight_smile:

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