Recursive Function Returns Undefined
The provided function calculates taxes using recursion, but it fails to stop the recursion. This issue arises from not returning a value within the recursive arm of the function.
Within the if (taxWage > minWage) block:
if (taxWage > minWage) { // calculates tax recursively calling two other functions difference() and taxStep() tax = tax + difference(taxWage) * taxStep(taxWage); var newSalary = taxWage - difference(taxWage); taxes(tax, newSalary); }
The code calculates taxes recursively but does not return a value or set returnTax. The absence of a return statement results in an undefined return value.
To rectify this, a return statement can be added to this arm:
if (taxWage > minWage) { // calculates tax recursively calling two other functions difference() and taxStep() tax = tax + difference(taxWage) * taxStep(taxWage); var newSalary = taxWage - difference(taxWage); return taxes(tax, newSalary); }
With this adjustment, the function will now return a value, preventing the recursion from continuing indefinitely.
The above is the detailed content of Why Does My Recursive Tax Calculation Function Return Undefined?. For more information, please follow other related articles on the PHP Chinese website!