Home > Web Front-end > JS Tutorial > Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?

Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?

Susan Sarandon
Release: 2024-12-19 22:04:12
Original
958 people have browsed it

Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?

Undefined Recursion in Tax Calculation

In this recursive tax calculation function:

function taxes(tax, taxWage) {
    var minWage = firstTier; //defined as a global variable
    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);
    } else {
        returnTax = tax + taxWage * taxStep(taxWage);
        return returnTax;
    }
}
Copy after login

the recursion fails to terminate. Specifically, the issue lies in the arm of the function that invokes the recursive call:

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);
}
Copy after login

Here, the function does not return any value or set the returnTax variable. When a function does not return explicitly, it defaults to returning undefined. Consequently, the recursion continues indefinitely, leading to undefined results.

To fix this issue, you should modify this part of the code as follows:

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);
}
Copy after login

This change ensures that the function returns the result of the recursive call, properly propagating the values up the recursion chain.

The above is the detailed content of Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template