Hi, I am solving the Javascript problem of creating a range of numbers through recursion. This is what I have and feel like I understand most of it. Now, the bit that I am unsure on (and seems to be wrong from reading up/watching tutorials) is the rangeOfNumbers(startNum, endNum) and arr=rangeOfNumbers(startNum++). Why is it wrong or faulty?
As I understand it, the startNum++ shows that the numbers increase by one each time. So why would it need to be endNum -1? I feel like I may have forgotten something, but just can’t remember/find it.
Here you say rangeOfNumbers requires two arguments
But you are only giving it one here
Also, you are falling into the difference between preincrement and postincrement with ++. You don’t need to mutate startNum, so I’d use startNum + 1 instead.
Ahh, okay! That makes sense, I didn’t realise that using ++ or – mutates the parameter. I have tried it with startNum + 1 and it didn’t work, only as ```(startNum, endNum -1)``. Not really sure why this is going on.
Also, I am struggling to understand why the code for the base case doesn’t work with if (endNum <= startNum) { return []; } even though it should theoretically work. If the start number is the same or less than the end number, then there should be the number returned, rather than going through the recursive function. I can see then that this causes the entire function to not work as expected, as it is all inter-connected.
// running tests
rangeOfNumbers(1, 5) should return[1, 2, 3, 4, 5].
rangeOfNumbers(6, 9) should return [6, 7, 8, 9].
Global variables should not be used to cache the array.
// tests completed
If both numbers are the same, then only one should appear on the console. But, the console would throw the comparison as false, so it would go to the ‘else if’ section and go through creating a sequence. As the values are the same, there wouldn’t be a sequence created.
Here is the updated code, without the bug on line 5 where there was only one parameter.
I can see that with this code, I get a sequence of the end number eg (1, 5) - as [5, 5, 5, 5, 5].
Ahh, I think I understand it(?) … So the computer looks at the code and goes through the second parameter first, and then the first parameter. This means that then the sequence decreases as going down from endNum to startNum (looking at it backwards). But, on console it is printed from start (smaller) number to end (larger) number.