Tell us what’s happening:
I’m getting confused in line 9 and line 10. When the program reaches last case that is (end_num - start_num === 2) it will return [start_num + 1]; (2+1).
How is it going to push value(line number 10) list.push(end_num - 1); and return list?
Please take a look at the repl.it link that I have given at the bottom.
Thanks in advance!!
Your code so far
var range = function(start_num, end_num)
{
if (end_num - start_num === 2)
{
return [start_num + 1];
}
else
{
var list = range(start_num, end_num - 1);
list.push(end_num - 1);
return list;
}
};
console.log(range(2,9));
Link to the challenge:
so is this a program that takes two numbers and gives back an array of all the numbers that are inside that range?
so if given (1,2) it should give back [], that is an empty array?
but if given (1,3) it should give back [2] only?
It would be good to get a link to the actual freecodecamp challenge so I can understand the goal and what you are given to begin with.
not at a computer right now so I can’t do much to help you but if you console log out your list right after line 10 you can see how the array is built
That’s a cool little demonstration of recursion there. I’m going to pinch that for my own notes
Anytime a function calls another function (synchronously, that is) the calling function is put on hold waiting for the return value from callee. This applies even when a function calls itself.
In your example you have at one point 5 copies of range waiting for the 6th copy to return.
In this case the last call to range
(that is when end_num - start_num === 2
) is the first to push onto the list, then it hands list back to the previous caller. Each caller pushes its end_num - 1
onto the list and returns it back to previous calling function.
Very last return is delivered to console.log(range(2,9));
Here’s your example - I put a ton o’ logging statements to document what / when things are happening.