Arr.push() issue in Use Recursion to Create a Range of Numbers

Tell us what’s happening:
Hi! I think I’m starting to understand recursion generally. However, what I don’t understand is how we can use push() in this case…
I know we set up an empty array in the if statement, but wouldn’t that only be established when endNum-startNum === 0? Until then, no array exists, so don’t we need to establish an empty array in the else statement in order to push something into it?

Your code so far


function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
  return [startNum];
}
else {
  var numbers = rangeOfNumbers(startNum, endNum - 1);
  numbers.push(endNum);
  return numbers;
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers

numbers.push(endNum) doesn’t happen until var numbers = rangeOfNumbers(startNum, endNum - 1) resolves, so we get a stack of function calls all waiting for the exit condition (endNum - startNum === 0) to be met.

For example, if we start with rangeOfNumbers(1, 3) this leads to us calling rangeOfNumbers(1, 2) which calls rangeOfNumbers(1, 1). That actually returns a value ([1]), so numbers inside rangeOfNumbers(1,2) is [1] and we push to it and it returns [1, 2]. Now that rangeOfNumbers(1, 2) has returned, the numbers in our original rangeOfNumbers(1, 3) is resolved to [1, 2]. We can push to it and return the final result.

Recursive calls is like setting up a bunch of dominoes. The exit condition is what tips the last one over.

5 Likes

Thank you, @ArielLeslie! This is such a good explanation. I’d been thinking of recursion a little backwards. :slight_smile: I appreciate your help!

I’m glad I could help.

Thank you!! This, with the “dominoes” analogy helped a lot. I have been trying to find a good explanation!

I’m glad I could help. Learning recursion is like learning yoga: at first it feels like you’re trying to twist your brain into unnatural shapes, but with practice, patience, and time it gives you flexibility and a strong core. :smiley:

1 Like

@ArielLeslie Thank you so much for this explanation. I was frustrated for about an hour trying to make sense of recursion in my head and I finally understand it now

Congratulations! It hurts all our brains at first.

1 Like