function sum(numbers) {
return tail_sum(numbers, 0);
}
function tail_sum(numbers, acc) {
if(numbers.length == 0) {
return acc;
}
return tail_sum(numbers.slice(1), acc + numbers[0]);
}
in the tail recursive version, function return value does not need to wait till the end to do it its calculations, so there's no huge stack here; only two levels.
sum([10, 5, 6, 7]);
tail_sum([10, 5, 6, 7], 0);
tail_sum([5, 6, 7], 10);
tail_sum([6, 7], 15);
tail_sum([7], 21);
tail_sum([], 28);
28;