Use Recursion to Create a Range of Numbers

My code works fine, and for the most part, I understand why it works. But…I do have a couple of questions if anyone can help me out:

function rangeOfNumbers(startNum, endNum) {
  if (endNum < startNum) {
    return [];
  } else {
    const range = rangeOfNumbers(startNum, endNum - 1);
    range.push(endNum);
    return range;
  }
};

Question the first:

When my if value returns brackets for an array, is that being returned specifically to the range variable? I don’t understand how this works unless that is the case, because of the range.push() function.

And for the second question:

Why is it ok for a const to be re-declared this way? This would normally throw an error, wouldn’t it?

Thanks in advance for anyone willing to talk me through this. I’m just trying to fully understand what’s happening, even if i know how to make it work.

Each function call is completely separate. There is no redeclaration inside of the same scope.

1 Like

Ok, that makes sense to me. It’s never actually being re-declared, just declared in another scope to run the function again.

Where does the actual array exist? I can understand that it’s created when endNum < startNum, but how does it come to be called range in this case? It must be, if range.push() works, but what I’m not understanding is, does that return statement return to that variable?

I’m just not wrapping my head around that part, still.

The function call has a return value here. Specifically, an array holding the range from startNum to endNum-1 is returned.

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