I’m trying to understand recursion. I came up with a function that calculates the sum of numbers in a range. In this case it’s numbers from 3 to 10.
var limit = 10;
function sumRange(value){
if(value===limit){
return value;
}
return value+sumRange(value+1);
}
sumRange(3);
Written like this the function seems to work fine with the limit being declared before the function.
However, when I refactor the code to look like this
function sumRange(value,limit){
if(value===limit){
return value;
}
return value+sumRange(value+1);
}
sumRange(3,10);
I get a ‘Maximum call stack size exceeded’ error. Can you help me understand why? Many thanks!
if(value===limit)
doesn’t work. It needs an actual value that will terminate the recursion.
2 Likes
function sumRange(value,limit){
if(value===limit){
return value;
}
return value + sumRange(value+1);
}
You’re not passing a limit
when you recurse, and value
will never equal undefined
, so you’re hosed. You can use closures to your advantage by creating a helper function inside of your main function.
1 Like
Thanks very much for your response. Could you give me an example of a helper function that would work in this case?
One possibility:
function sumRange(value, limit) {
return _s(value);
function _s(value) {
if(value === limit) return value;
return value + _s(value + 1);
}
}
1 Like
Cool! So with each recursion it returns the current value
, then proceeds to compare that to the limit
and either returns the current value or runs the function again until value===limit
.
Many thanks!!!