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
.
Comments
-
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 about 5 yearsThis helped, but I'm interested in knowing why
return
is necessary for the recursion to operate correctly. -
dsh about 5 yearsIf you want your function to return a value, then you must return a value. In javascript, a function without a
return
will returnundefined
. 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 needsreturn
. You can explore this by stepping through the function in a debugger. -
artomason about 5 yearsI 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.