Recursive function returns undefined

10,681

Solution 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

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.

Share:
10,681
raam86
Author by

raam86

Solving other peoples problems for money #SOreadytohelp

Updated on June 29, 2022

Comments

  • raam86
    raam86 almost 2 years

    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.

  • artomason
    artomason about 5 years
    This helped, but I'm interested in knowing why return is necessary for the recursion to operate correctly.
  • dsh
    dsh about 5 years
    If you want your function to return a value, then you must return a value. In javascript, a function without a return will return undefined. Recursion itself doesn't require a return (eg: print out the nodes in a tree), but if you want the function to return something then it needs return. You can explore this by stepping through the function in a debugger.
  • artomason
    artomason about 5 years
    I think what confused me about it how it works in JavaScript was the fact that I expected that calling the function itself was enough to instantiate recursion. For instance; incrementing a number then calling the function and passing it back to itself. Either way, this was helpful, I was just curious.