Basic JavaScript - Use Recursion to Create a Countdown

Hey, I need help understanding recursion in-depth in js.
when I add console .log to the example to see what’s it doing step by step during the recursion, this is what I get for this code:

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    **console.log(countup(n - 1));**
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

the console shows:

[]
[ 1 ]
[]
[ 1, 2 ]
[]
[ 1 ]
[]
[ 1, 2, 3 ]
[]
[ 1 ]
[]
[ 1, 2 ]
[]
[ 1 ]
[]
[ 1, 2, 3, 4 ]
[]
[ 1 ]
[]
[ 1, 2 ]
[]
[ 1 ]
[]
[ 1, 2, 3 ]
[]
[ 1 ]
[]
[ 1, 2 ]
[]
[ 1 ]
[]
[ 1, 2, 3, 4, 5 ]

it seems to restart the array every time until it get to 5 and I got confused, I don’t fully understand what is happening in every step in the call stack

The thing is , your console.log makes additional function calls and it confuses you even more, for this case console-logging is not the best way to understand stuff

Familiar with this tool below?
https://pythontutor.com/visualize.html#mode=edit

Grab your code(preferrably without console.log line, it will add some more confusion), and check it there. If you will have more questions after, feel free to deliver them)

Edit. I guess you can use logging also, like this:

function countup(n) {
  if (n < 1) {
    return [];
  } else {    
    const countArray = countup(n - 1);
    console.log(countArray);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

And blur your code please, it’s working solution, it may be a spoiler for other people

I suggest you write console.log(countArray) instead of console.log(countup(n - 1)) to make things less confusing

or even console.log({countArray, n})

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