Confusion with Recursion

I tried different ways, it doesn’t seem to work. Can someone tell me what I’m doing wrong? Thank you.

  **My code so far**

function rangeOfNumbers(startNum, endNum) {
  if (endNum == startNum) {
    return [startNum];
  } else {
    /*startNum = startNum <= endNum;*/
    const myArray = rangeOfNumbers(endNum - startNum);
    myArray.push(endNum);
    myArray.unshift(startNum);
    return myArray;
  }
}

How many parameters does rangeOfNumbers take?

1 Like

Two parameters. Can you also explain why I had to use square braces in the third line around startNum ?

I’m not trying to answer your question, just noticed something that i didn’t get.
How do you push a number onto another number if the last is not an array or in one? so far i learned that you can push an element to an array not to number or a string. Unless when you do that javascript creates an array for them.just guessing.
Thank you.

So why are you calling it with only one?

The square brackets mean you are creating an array, the output of the function should always be an array

But he did it only in the if statement not the else statement, so how is the else statement output gonna be ? Will it get outputed in an array automatically?
I see in that code that he is trying to push a value to the function call, does that mean that the function call’s returned value is in an array already?

Yes, the function returns an array

1 Like

Hi @zak,
Is always a good idea to remember that an algorithm or solution is different from its implementation.

… Will it get outputed in an array automatically?

… does that mean that the function call’s returned value is in an array already?

… i learned that you can push an element to an array not to number or a string. Unless when you do that javascript creates an array for them.just guessing.

JS(the implementation) uses some abstractions: call stack and nested calls that you need to know to answer your questions.

I tried to explain this in another thread:

Cheers and happy coding :slight_smile:

1 Like