Great job! I didn’t realize that the curriculum hadn’t covered Array.concat() yet so I apologize for leading you down that path. But at the same time that’s awesome that you were able to figure it for yourself!
Yes, you can use Array.push() to solve this and it only takes a few extra lines of code in the else
block but personally I think it is conceptually easier to solve it with concat(). Also, since you are adding startNum
to the beginning of the array you would need to use Array.unshift() instead of Array.push(). But in order to use unshift() you would need to create an extra temporary array variable in the else
block and save the recursive function call to that variable, then add startNum
to the beginning of that array with unshift(), then return the array. As for the reason you have to add these extra steps in order to use unshift(), I’ll direct you to the MDN docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
The one sentence explanation at the top includes the reason. Remember, both the if
and else
blocks of your code have to return an array with numbers.
As to how this works, you should definitely take the time to understand it so you have a better feel for recursion. My suggestion would be to pencil it out on paper. Go through the steps on paper just like the computer goes through them. I’ll get you started.
If your args aren’t equal then you will hit the else
block. So let’s say the original call is
rangeOfNumbers(1,3);
You will trigger the else
block and the original return value will be
[1].concat(rangeOfNumbers(2,3))
Now you have the first number in your return array set to 1. And we know that the concat() method that calls rangeOfNumbers is going to return an array of numbers because rangeOfNumbers always returns an array on numbers.
So now just focus on rangeOfNumbers(2,3)
in the original return value above. What is that going to return? You can replace rangeOfNumbers(2,3)
in the original return value with the actual return value of rangeOfNumbers(2,3)
. And then keep doing this until you hit the base case. You should be able to see how the original return array is built up using recursion.