Use-recursion-to-create-a-range-of-numbers----newproblem

Tell us what’s happening:
Describe your issue in detail here.

Please describe the whole code what’s it do line by line. Thank you in advance.

**Your code so far**

function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
    return [startNum];
} else {
    const newNum = rangeOfNumbers(startNum, endNum - 1);
    newNum.push(endNum);
    console.log(newNum);
    return newNum;
}
}
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/97.0.4692.71 Safari/537.36

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

I might be slightly confused here because what you posted works. Did you code this yourself or did you copy a working solution and just want it explained?

As far as explaining, I don’t think you need a line by line explanation, do you? I’m guessing you understand what the following block of code does:

if (endNum - startNum === 0) {
    return [startNum];
}

So in order to keep us from having to guess and type out unnecessary information, please be a little more specific and let us know exactly what you do not understand.

1 Like

I applied basic recursive rule here but one thing got me stuck.
Just this else step,
i don’t get it by comparing with values,
If i pass any value, lets say ((1, 5)… -

const newNum = rangeOfNumbers(1, 5 - 1); //which is (1, 4)
newNum.push(5); // which should be like (1, 4, 5) if i’m not wrong.

thank you for taking time to read my post…

Sorry, but you’re just slightly wrong :slight_smile:

newNum will hold an array. That array will be the return value of rangeOfNumbers(1, 4). So what will rangeOfNumbers(1, 4) return? Well, you have to start the whole process over again because it’s a new recursive function call.

1 Like

I didn’t declared any array. Where and how Array exist in here?

The function always returns an array. Look at the base case, it returns an array. Also, how could you do:

const newNum = rangeOfNumbers(startNum, endNum - 1);
newNum.push(endNum);

If newNum wasn’t an array. You have to have an array in order to use the push method.

1 Like