Habushu
September 16, 2022, 12:33am
1
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?
**Your code so far**
function rangeOfNumbers(startNum, endNum) {
if (endNum < startNum) {
return [];
} else {
const numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}
**Your browser information:**
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
Link to the challenge:
hbar1st
September 16, 2022, 2:04am
2
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;
}
}
Hopefully this will help you see what is happening.
I have created a flow chart with
draw.io to explain what is happening. Hope this help you.
ugwen
September 16, 2022, 12:48pm
4
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))
hbar1st
September 16, 2022, 12:53pm
5
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?
ugwen
September 16, 2022, 12:54pm
6
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)
system
Closed
March 18, 2023, 12:55am
7
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.