# Need Help to Explain Basic JavaScript - Use Recursion to Create a Range of Numbers

Tell us what’s happening:
Hello everyone,

your help will be needed to explain this chapter to me. I’ve pass this exercise with a bit help from the hints. However im not quite sure how this can make a “loop” cause it looks like a one time call to me? why do we need - 1 after the endNum? and how is that showing array as a result? is it because we use .push() and thats automatically makes an array?

function rangeOfNumbers(startNum, endNum) {
if (endNum < startNum) {
return [];
} else {
const numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}

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

Challenge: Basic JavaScript - Use Recursion to Create a Range of Numbers

Try to run this function instead (with some logs)

function rangeOfNumbers(startNum, endNum) {
console.log(“Enter-“+ startNum + “, “+ endNum +”\n”);
if (endNum < startNum) {
return [];
} else {
const numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
console.log(“after push: “+numbers.toString() +”\n”);
return numbers;
}
}

I have created a flow chart with draw.io to explain what is happening. Hope this help you.

i found this helpfull for myself but i struggled to get your code as is working and wrote simplified:

function rangeOfNumbers(startNum, endNum) {
console.log('startnum/endnum @start:',startNum ,endNum );
if (endNum < startNum) {
return [];
} else {
const numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
console.log('after push:',numbers);
return numbers;
}
}
console.log('result', rangeOfNumbers(1,3))

yes sorry, my cellphone uses the wrong type of double-quotes (they needed to be changed to work)

Did you have any further question as you saw the log?

me? no, it works fine with the fixes, and i only fixed the log lines. the code is fine.
(‘\n’ always seems to be default in fcc editor)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.