Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 691
raam86 Avatar asked Oct 05 '12 00:10

raam86


People also ask

Why is my function returning undefined?

A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Do recursive functions return a value?

Definition of Recursion Recursion is a method of programming or coding a problem, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition satisfies the condition of recursion, we call this function a recursive function.

Does return stop a recursive function?

Aside from that, if you've called your recursive function a given number of times, returning from the function would return you to the previous call of that function. A return statement won't stop all the prior recursive calls made from executing.

What is recursive function in Javascript?

Recursion is a process of calling itself. A function that calls itself is called a recursive function. The syntax for recursive function is: function recurse() { // function code recurse(); // function code } recurse(); Here, the recurse() function is a recursive function.


1 Answers

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); 
}
like image 159
jfriend00 Avatar answered Oct 07 '22 02:10

jfriend00