Final recursion problem

Tell us what’s happening:

This is my code for the 110/110 problem on the basic Javascript module.
The problem is to have a recursive function that makes a range between ( startNum, endNum)

ex. rangeOfNumbers (1, 5);
myArr = [1, 2, 3, 4, 5];

This is as complete a code as I can figure out. (without looking at the ‘hints’ and having the satisfaction taken away).

I think it would check if the values are equal, if not it calls upon the recursive function again to increase and recheck if the value is equal… and so on… and so on…

Once they are the same it would return the startNum increased to the value of endSum [5], then the function would continue off the stack and unshift a decreasing startNum value.
[5]
[4,5]
[3,4,5]
[2,3,4,5]
[1,2,3,4,5]

and the function would be complete. But this isn’t the case and there’s no breakpoints to check either.

Is my code not written in a way that does what I explained?
Am I missing some variable?

Your code so far


function rangeOfNumbers(startNum, endNum) {
const myArr = [];

if (startNum === endNum)
{
myArr.push(startNum);
return myArr;
}
else {

rangeOfNumbers(startNum + 1, endNum);
myArr.unshift(startNum);
return myArr;
}
};

Your browser information:

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

You aren’t capturing the return value of this function call.

1 Like

Thank you! It’s something I played around with but any work I did on it usually resulted in not returning an array and I thought I was going on the wrong path. How would one go about capturing that?

1 Like

Something like

thisArray = myFunction(foo);

You’re losing me. Unfortunately that’s a little vague on how it applies to this.

Your function call rangeOfNumbers(startNum + 1, endNum) returns a value.

You save the output of a function call to a variable by using myVariable = myFunction(myArgs).

For example,

// Function definition
function myAdd(num1, num2) {
  return num1 + num2;
}

// Variables
let myFirstNum = 1;
let mySecondNum = 2;
let myResult;

// Function call
myResult = myAdd(myFirstNum, mySecondNum);

// Check result
console.log(myResult); // Should be 3

Another example would be from the previous exercise

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    // LOOK RIGHT HERE AT THE RETURN ARRAY BEING CAPTURED
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]