Why does pushing to the array before calling the recursive function return [1]

Tell us what’s happening:
The code below works when I unshift after the recursive call but does not work when it is done before and I have gone through the solutions to find the answer but I did not get it myself. My original code kept pushing back [5] or whatever the endNum was. My previous code was:

function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){
return [endNum];
} else {

  var arr = [];
  arr.unshift(startNum)
  var arr = rangeOfNumbers(startNum + 1,endNum);
  //arr.unshift(startNum);
  return arr;

}
};

console.log(rangeOfNumbers(1,5));
// Console Log would return [5] for the above code.

My question is to help me understand why the code would not push the numbers to the array and if I am correct in my understanding that the code is iterating through the recursive function until startNum = 5 and is === to endNum so it return [endNum].

  **Your code so far**

function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){  
  return [endNum];
} else {
   
    var arr = rangeOfNumbers(startNum + 1,endNum);
    arr.unshift(startNum);
    return arr;
}
};

console.log(rangeOfNumbers(1,5));
  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

If you unshift before tme function call, arr has not been set to the return value of the recursive call yet, so it’s just an empty array.

2 Likes

That makes sense, I guess I was getting confused with the recursive function being called into the stack and then kicking back all the answers to the function. My thought was
arr.unshift(startNum) is going to kick out arr = [1]
var arr = rangeofNumbers(startNum+1, endNum) would push 2 to the array so [1,2] and so forth.

but each run of the function in the stack is rewriting the array as blank with a single number?

These three lines say

  1. Call rangeOfNumbers to get an array with the values from startNum + 1 to endNum and save that array to arr

  2. unshift() the number startNum onto this array

  3. return this array

1 Like