Why we assign a variable to the recursive call

/* why are we assigning the recursive call in numbers variable, can’t we just call the recursive fn and push… let numbers = recursive call*/

function rangeOfNumbers(startNum, endNum) {

if(startNum>endNum)

{

return ;

}

else

{

let numbers = rangeOfNumbers(startNum,endNum-1);

/ why are we assigning the recursive call in numbers variable, can’t we just call the recursive fn and push it in the array/** :thinking:

numbers.push(endNum);

return numbers;

}

};
console.log(rangeOfNumbers(6,9));

Hello, and welcome to the forum! Please format the code better so it becomes more readable.

As for your question, it has to do with how assignment works in functions and the return statement.

Consider this code:

function recursive(msg, val = 0){
  if(val >= 3){
    return msg;
  }
  else{
    return recursive(msg + "ha", ++val)
  }
}
let result = recursive("ha");
console.log(result); //--> "hahaha"

This will print "hahaha".

In why it does that, we can refer to the call stack.

JavaScript will put a function onto the stack. When that function is called and returned, it is popped from the stack.

I, myself do not know much about this. All I know is that it is a big thing in this because it helps keep track of the returns in the recursive function.

First, it will execute the function the first time. Since it returns the execution of another function, the program will add a new function call to the stack, which then executes before the first function call is returned. It keeps on going like that until the return value does not return a new function call. This is what happens in our little function here.

As to why we assign a variable to it, is because the return value is much less messy in that we don’t have to have a variable outside of the function to hold the numbers. It is all in the function’s scope so we don’t have to have more variables in our code.

1 Like

Extended

function recursive(msg, lim = 3, val = 0){
  if (++val >= lim) {    //  base case
    return msg;
  }
  else{
    return recursive(msg + "ha", lim, val)
  }
}
let result = recursive("ha", 7);
console.log(result)    //  hahahahahahaha
2 Likes

Thanks for the help :smiley: Got it

It was more of an example, but whatever.

Just more info for people to look over and compare and conclude with!

1 Like