Home > Back-end >  Getting 'undefined' when trying to return a value from a recursive function
Getting 'undefined' when trying to return a value from a recursive function

Time:10-16

So I have this recursive function which takes in two parameters, factor and width. The factor will decrement in every recursive instance by 0.05. And in every instance it will be multiplied with width to get a value.

If this value is greater than 900 then the recursive function will continue. If it is less than 900 then it will stop and return the factor value.

Right now I'm getting undefined but if I log all the factors then I can see that there are numbers before undefined but it stops with undefined.

How can I get the factor value which is just before undefined?

Here's the snippet:

function findFactor(factor, width) {

  let nextFactor = factor - 0.05;
  let value = width * nextFactor;

  console.log(nextFactor);

  if (value < 900) {
    return nextFactor;
  } else {
    findFactor(nextFactor, width);
  }

}

console.log(findFactor(1, 2400));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are properly returning the result in case if (value < 900) {. However, you forgot to return the result of the subsequent recursive call. Adding return should solve your problem:

else {
  return findFactor(nextFactor, width);
}
  • Related