Use Recursion to Create a Range of Numbers: problem returning/pushing values

Tell us what’s happening:
Hi! This is the first time im participating in the forum so im sorry if my code explanation doesn’t read that well.
I think i ve been getting stuck around the return part of a function. What’s happening here? Why does “return result.unshift(startNum);” not add any numbers to the array inside the variable i’ve created?

Your code so far

function rangeOfNumbers(startNum, endNum) {
//Set a base case
if (startNum = endNum) {
  var result = [];
//startNum has been increased to the same value as endNum so i push it to be the last element of my array
return result;
} else {
//increase my startNum for the next function
rangeOfNumbers(startNum +1, endNum);
//unshift startNum 
return result.unshift(startNum);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

You’re not making use of the returned value of rangeOfNumbers(startNum +1, endNum);. The recursive calls to a function do not change the data in the caller. Like any other function, you have to uses the returned value for it to do anything.


In addition to the above, if you look at the documentation, unshift returns the current length of the array. You want to unshift the value into the array and then return the modified array.

1 Like

Thank you for helping me!
So should i try to unshift the function itself, like this?
else {
result.unshift(rangeOfNumbers(startNum +1, endNum));
return result;
Because it keeps returning only the first function. I’ve also tried to make a new variable to see if calling a function inside the unshift was the problem, like so:

var funResult = rangeOfNumbers(startNum +1, endNum);

return result;

and it still doesnt work

Thank you! that must have gone over my head :slight_smile: