Array and Recursion

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

Hello, I am a new to programming.
I don’t see the array declaration statement like below in the function above.

var numbers = [];

so how is numbers array already when numbers.push(endNum) and return numbers?

Sure. They are declaring an array literal.

When you do something like:

var numbers = [];

You are creating an array with []. It then takes the reference (memory address) and stores it in the variable numbers.

In the code above, as it goes recursively through the function, it keeps hitting the else and recalling the function, putting a bunch of function calls on the call stack. Then it finally reaches the if condition and creates an array literal with [startNum]. This is where the array is created. That reference doesn’t get stored in a variable but just gets returned back to the previous caller that resumes and doesn’t its push and then returns that same reference back to its caller, and so on and so on, unwinding itself off the call stack, passing (returning) its reference back. Then the final one on the call stack passes that same reference (there was ever only one) back to wherever it was called. So, if you have:

const myArrayOfNumbers = rangeOfNumbers(1, 10);

then _ rangeOfNumbers_ now holds the reference to that array.

Or, if you have

console.log(rangeOfNumbers(1, 10));

then that reference never really stored anywhere, except in the call stack as its passed console.log, and then it disappears once console.log is done with it.

You’ve got a few confusing concepts going on here:

Memory management is confusing. In some languages you actually have to manage it yourself, allocating and freeing it up yourself. That’s a huge pain. It’s nice the JS takes care of all of that for you. But that also makes it a little harder to understand.

If you haven’t seen it before the distinction between creating a nameless literal and storing something in a variable can be confusing.

And finally recursion will mess anyone’s head up. Your confusion is normal and it’s a sign that you’re paying attention.

3 Likes

Thank you. I keep reading your explanation over and over. I feel like I understand 51% of it, although I marked it as solution. I will just need to stick w/ it enough until my brains clicks and goes ah ha.

Yeah, just keep at it. This is hard stuff - that’s why it pays well.

1 Like