About Recursion

About Recursion

Hello everyone,

I’m trying to understand better the concept about Recursion,

function count(n) {
  if (n === 1) {
    return [1];
  } else {
    var numbers = count(n - 1); 
    return numbers;

The steps:
a. The function counting backwards, from 5 to 1.

b. When 1 === 1 is true, the function return [1] and assign it to var numbers.

c. numbers.push(n) pushing the call stack to numbers.
(starting from the last execution 2 to the first execution 5).

d. Then the function return the value:
return numbers

[1, 2, 3, 4, 5]

I got it right?

yeah, imagine stack, like the stack of cards, and each new recursion call goes on top of each other until it reaches 1 (so called exit condition) and then you go back in Last-In-First-Out order until you reach the initial call :slight_smile:

1 Like

Awesome! Thanks Igor :sunglasses: