'Recursive function returns undefined

I have a function which calculates taxes.

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;
    }
} 

I can't see why it doesn't stop the recursion.



Solution 1:[1]

In this arm of your function:

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); 
}

you are not returning a value from the function or setting returnTax. When you don't return anything, the return value is undefined.

Perhaps, you want this:

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); 
}

Solution 2:[2]

There is a bug with your recursion:

taxes(tax, newSalary);

You don't return anything when the condition in the if evaluates to true. You need to change that to:

return taxes(tax, newSalary);

You have the necessary return statement in the else.

Solution 3:[3]

For example taxes(tax, newSalary); returns 100;

taxes(tax, newSalary); // undefined

You expect to see 100 because you called taxes(tax, newSalary) recursively but in fact you got the value (100) and you need to return this value.

return taxes(tax, newSalary); // 100
// simply it's the same as
// return 100
// because taxes(tax, newSalary) returned 100

after return 100 you will get this value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 dsh
Solution 3 nikolozz