28
loading...
This website collects cookies to deliver better user experience
sum
function as an example:function sum(input: number[] = [], output: number = 0): number {
if (!input || input.length === 0) {
return output;
}
output += input.pop();
return sum(input, output);
}
output
parameter.output
to 0, and returns default upon malformed data.null
value being passed in, an incorrect type, an array reaching zero length, an integer exceeding a certain value, etc. If the conditions are met, this is where you return output;
and exit your recursion..pop()
on an array that will eventually reach 0 in length.const value = input.pop();
...
input.push('lorem ipsum');
i > 999
this function will stop. DELETE
or UPDATE
query in SQL and saw 1,604,201 rows affected
, then you'll understand the benefit of this.function recursion(index = 0, max = 10) {
// Top layer determines why we exit
if (index >= max) {
return index;
}
// Middle layer inches us toward our exit
index++;
// Bottom layer continues our recursion
return recursion(index, max);
}