Solution 3 of the challenge: Use Recursion to Create a Range of Numbers!

Hello, what’s happening in here: “[…rangeOfNumbers(startNum, endNum - 1), endNum ]” the … means what?

The original answer:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];

The … is the spread operator.

1 Like

I looked into that myself. Would you mind explaining how it works in this scenario? I ran it through PythonTutor, which helped, but would love some clarification as to what’s actually happening.
I’ve included a photo of step 4, when it first runs line 4, and i’m finding it a little confusing. Why is it only returning startNum and endNum - 1, and not endNum, also? Could you illuminate what’s happening on this line? Thanks.

1 Like

The line is making a recursive call. The figure is showing the state of second function call to rangeOfNumbers. This is recursion, where the function calls itself until the end condition is met. You should keep running the code until you see the frame with 4 and 4 for startNum and endNum. You should see four frames. Keep running. The fourth frame will return [4] to the third frame and the third frame returns [4,5] to the second frame. Then [4, 5, 6] gets returned the first frame. And finally the solution [4, 5, 6, 7] goes back to the first call.

1 Like

This is a nice use of the spread operator with recursion.
Expression like

[...[2, 3, 4], 5]

will result in

[2, 3, 4, 5]

Calling rangeOfNumbers(2, 5) returns [2, 3, 4, 5]. To solve recursively, you can recurse to create one smaller array [2, 3, 4] and the use the spread operator to get the final answer. So the expression becomes

[...rangeOfNumbers(2, 4), 5]

In general context, you replace these literals with the parameters.


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