Explain this recursive

Hello!

Do the following exercise:

count(3);

n = 3;
n === 1? false // return [1] skipped.
// Here count is called again, hence this steps is paused.
var numbers = count(n - 1); // n would be 2
# STEP1

n = 2;
n === 1? false // return [1] skipped.
// Here count is called again, hence this steps is paused.
var numbers = count(n - 1); // n would be 1
// Here the function is paused while the count(n-1) is executed
#STEP2

n = 1;
n === 1? true // an array with one is returned.

// Now the function call retraces its steps (yep, backwards now)
#Continue with STEP2
// Remember, n = 2
numbers = [1];
numbers.push(2);
return [1, 2];

#Continue with STEP1
// Remember, n = 3
numbers = [1, 2];
numbers.push(3);
return [1, 2, 3];

It helps me understand some algorithms, I hope it helps You too :slight_smile:.

8 Likes